<?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\FailedMessage;
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;

/**
 * 失败消息查看接口
 *
 * 仅 admin 角色可访问，展示 Consumer 处理失败的消息记录
 */
#[OA\Tag(name: 'Failed Messages', description: '失败消息查看')]
#[Controller(prefix: "/api/v1/failed-messages")]
#[Middleware(AuthMiddleware::class)]
#[Middleware(PermissionMiddleware::class)]
class FailedMessageController extends AbstractDataController
{
    protected function getModelClass(): string
    {
        return FailedMessage::class;
    }

    protected function getListFields(): array
    {
        return [
            'id', 'error_id', 'data_type', 'platform', 'platform_id',
            'company_id', 'store_id', 'error_type', 'error_message',
            'retry_count', 'message_id', 'failed_at', 'created_at',
        ];
    }

    protected function getDetailFields(): array
    {
        return [
            'id', 'error_id', 'data_type', 'platform', 'platform_id',
            'company_id', 'store_id', 'error_type', 'error_message',
            'error_code', 'error_trace', 'original_message',
            'retry_count', 'message_id', 'failed_at', 'created_at',
        ];
    }

    protected function getAllowedFilters(): array
    {
        return [
            'data_type' => 'exact',
            'platform_id' => 'exact',
            'error_type' => 'like',
            'failed_at_from' => 'date_from',
            'failed_at_to' => 'date_to',
        ];
    }

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

    /**
     * 失败消息列表
     */
    #[OA\Get(
        path: '/failed-messages',
        summary: '失败消息列表',
        description: '获取 Consumer 处理失败的消息列表，支持分页、按数据类型/平台/时间筛选。仅 admin 可访问。',
        security: [['bearerAuth' => []]],
        tags: ['Failed Messages'],
        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: 'data_type', in: 'query', required: false, description: '数据类型精确筛选（order/product/refund）', schema: new OA\Schema(type: 'string', enum: ['order', 'product', 'refund'])),
            new OA\Parameter(name: 'platform_id', in: 'query', required: false, description: '平台 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'error_type', in: 'query', required: false, description: '异常类名模糊搜索', schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'failed_at_from', in: 'query', required: false, description: '失败时间起始（含）', schema: new OA\Schema(type: 'string', format: 'date', example: '2026-01-01')),
            new OA\Parameter(name: 'failed_at_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/FailedMessageList')),
                        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: '/failed-messages/{id}',
        summary: '失败消息详情',
        description: '获取失败消息详情，含完整错误堆栈和原始消息体。仅 admin 可访问。',
        security: [['bearerAuth' => []]],
        tags: ['Failed Messages'],
        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', ref: '#/components/schemas/FailedMessageDetail'),
                ])
            ),
            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
    {
        return parent::show($id);
    }
}
