<?php

declare(strict_types=1);

namespace App\Controller\Api\V1;

use App\Controller\AbstractDataController;
use App\Middleware\AuthMiddleware;
use App\Middleware\PermissionMiddleware;
use App\Model\OrderItem;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;

/**
 * 订单项管理接口
 *
 * 返回所有 parsed 字段（OrderItem 无 raw/hash，仅 Normal Category）
 */
#[OA\Tag(name: 'Order Items', description: '订单项管理')]
#[Controller(prefix: "/api/v1/order-items")]
#[Middleware(AuthMiddleware::class)]
#[Middleware(PermissionMiddleware::class)]
class OrderItemController extends AbstractDataController
{
    protected function getModelClass(): string
    {
        return OrderItem::class;
    }

    protected function getListFields(): array
    {
        return [
            'id', 'company_id', 'platform_id', 'store_id', 'order_id',
            'platform_order_id', 'sub_order_id', 'platform_product_id',
            'product_sku', 'unit_price', 'quantity', 'discount', 'total',
            'created_date',
        ];
    }

    protected function getDetailFields(): array
    {
        return [
            'id', 'company_id', 'platform_id', 'store_id', 'order_id',
            'platform_order_id', 'sub_order_id', 'sub_order_type_id',
            'product_id', 'platform_product_id', 'product_sku', 'product_barcode',
            'unit_price', 'quantity', 'discount', 'total',
            'created_date', 'ext', 'created_at', 'updated_at',
        ];
    }

    protected function getAllowedFilters(): array
    {
        return [
            'company_id' => 'exact',
            'platform_id' => 'exact',
            'store_id' => 'exact',
            'order_id' => 'exact',
            'platform_order_id' => 'exact',
            'platform_product_id' => 'exact',
            'product_sku' => 'exact',
            'created_date_from' => 'date_from',
            'created_date_to' => 'date_to',
        ];
    }

    protected function getDefaultSort(): string
    {
        return 'created_date';
    }

    /**
     * 订单项列表
     */
    #[OA\Get(
        path: '/order-items',
        summary: '订单项列表',
        description: '获取订单项列表，支持分页和多维度筛选。OrderItem 无 raw/hash 字段，仅提供 Normal 接口。',
        security: [['bearerAuth' => []]],
        tags: ['Order Items'],
        parameters: [
            new OA\Parameter(name: 'page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 1)),
            new OA\Parameter(name: 'per_page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 15, maximum: 100)),
            new OA\Parameter(name: 'company_id', in: 'query', required: false, description: '公司 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'platform_id', in: 'query', required: false, description: '平台 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'store_id', in: 'query', required: false, description: '店铺 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'order_id', in: 'query', required: false, description: '内部订单 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'platform_order_id', in: 'query', required: false, description: '平台订单 ID 精确筛选', schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'platform_product_id', in: 'query', required: false, description: '平台商品 ID 精确筛选', schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'product_sku', in: 'query', required: false, description: 'SKU 编码精确筛选', schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'created_date_from', in: 'query', required: false, description: '创建时间起始（含）', schema: new OA\Schema(type: 'string', format: 'date', example: '2026-01-01')),
            new OA\Parameter(name: 'created_date_to', in: 'query', required: false, description: '创建时间截止（含）', schema: new OA\Schema(type: 'string', format: 'date', example: '2026-12-31')),
        ],
        responses: [
            new OA\Response(
                response: 200,
                description: '获取成功',
                content: new OA\JsonContent(properties: [
                    new OA\Property(property: 'code', type: 'integer', example: 0),
                    new OA\Property(property: 'message', type: 'string', example: '获取成功'),
                    new OA\Property(property: 'data', properties: [
                        new OA\Property(property: 'items', type: 'array', items: new OA\Items(ref: '#/components/schemas/OrderItem')),
                        new OA\Property(property: 'total', type: 'integer', example: 100),
                        new OA\Property(property: 'page', type: 'integer', example: 1),
                        new OA\Property(property: 'per_page', type: 'integer', example: 15),
                    ], type: 'object'),
                ])
            ),
            new OA\Response(response: 401, description: '未认证', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
            new OA\Response(response: 403, description: '无权限', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
        ]
    )]
    #[RequestMapping(path: "", methods: "GET")]
    public function index(): ResponseInterface|array
    {
        return parent::index();
    }

    /**
     * 订单项详情（含父订单摘要）
     */
    #[OA\Get(
        path: '/order-items/{id}',
        summary: '订单项详情',
        description: '获取订单项详情，返回完整字段和关联的父订单摘要信息。',
        security: [['bearerAuth' => []]],
        tags: ['Order Items'],
        parameters: [
            new OA\Parameter(name: 'id', in: 'path', required: true, description: '订单项 ID', schema: new OA\Schema(type: 'integer')),
        ],
        responses: [
            new OA\Response(
                response: 200,
                description: '获取成功',
                content: new OA\JsonContent(properties: [
                    new OA\Property(property: 'code', type: 'integer', example: 0),
                    new OA\Property(property: 'message', type: 'string', example: '获取成功'),
                    new OA\Property(property: 'data', type: 'object', allOf: [
                        new OA\Schema(ref: '#/components/schemas/OrderItem'),
                        new OA\Schema(properties: [
                            new OA\Property(property: 'parent_order', type: 'object', nullable: true, description: '父订单摘要信息'),
                        ]),
                    ]),
                ])
            ),
            new OA\Response(response: 401, description: '未认证', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
            new OA\Response(response: 403, description: '无权限', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
            new OA\Response(response: 404, description: '数据不存在', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
        ]
    )]
    #[RequestMapping(path: "{id}", methods: "GET")]
    public function show(int $id): ResponseInterface|array
    {
        $result = parent::show($id);

        // 404 响应直接返回
        if ($result instanceof ResponseInterface) {
            return $result;
        }

        // 追加父订单摘要
        $order_item = $result['data'];
        $result['data'] = $order_item->toArray();

        $parent_order = $order_item->getParentOrder();
        $result['data']['parent_order'] = $parent_order ? [
            'id' => $parent_order->id,
            'platform_order_id' => $parent_order->platform_order_id,
            'order_status_id' => $parent_order->order_status_id,
            'total_amount' => $parent_order->total_amount,
            'total_paid' => $parent_order->total_paid,
            'created_date' => $parent_order->created_date?->toDateTimeString(),
            'paid_date' => $parent_order->paid_date?->toDateTimeString(),
        ] : null;

        return $result;
    }
}
