<?php

declare(strict_types=1);

namespace App\Controller\Api\V1;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Middleware\PermissionMiddleware;
use App\Model\Company;
use App\Model\Store;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use OpenApi\Attributes as OA;

#[OA\Tag(name: 'Companies', description: '公司管理')]
#[Controller(prefix: "/api/v1/companies")]
class CompanyController extends AbstractController
{
    /**
     * 公司列表（受 scope 过滤）
     *
     * administrator 可见全部，developer/accessor 仅可见权限范围内的公司
     */
    #[OA\Get(
        path: '/companies',
        summary: '公司列表',
        description: '获取公司列表，支持按 name/label 模糊搜索，受 scope 过滤',
        security: [['bearerAuth' => []]],
        tags: ['Companies'],
        parameters: [
            new OA\Parameter(name: 'name', in: 'query', required: false, description: '公司名称模糊搜索（匹配 name 或 label）', schema: new OA\Schema(type: 'string')),
        ],
        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: 'array', items: new OA\Items(properties: [
                        new OA\Property(property: 'id', type: 'integer', example: 1),
                        new OA\Property(property: 'name', type: 'string', example: 'acme'),
                        new OA\Property(property: 'label', type: 'string', example: '阿克米公司'),
                        new OA\Property(property: 'enabled', type: 'boolean', example: true),
                        new OA\Property(property: 'ext', type: 'object', nullable: true),
                        new OA\Property(property: 'created_at', type: 'string', format: 'date-time'),
                        new OA\Property(property: 'updated_at', type: 'string', format: 'date-time'),
                    ])),
                ])
            ),
            new OA\Response(response: 401, description: '未认证', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
        ]
    )]
    #[RequestMapping(path: "", methods: "GET")]
    #[Middleware(AuthMiddleware::class)]
    #[Middleware(PermissionMiddleware::class)]
    public function index(): array
    {
        $scope_type = $this->request->getAttribute('scope_type');
        $scope_ids = $this->request->getAttribute('scope_ids', []);

        $query = Company::query();

        // scope 过滤
        if ($scope_type === 'store') {
            // 从 store_ids 反查 company_ids
            $company_ids = Store::query()
                ->whereIn('id', $scope_ids)
                ->distinct()
                ->pluck('company_id')
                ->toArray();
            $query->whereIn('id', $company_ids);
        } elseif ($scope_type === 'platform') {
            $company_ids = Store::query()
                ->whereIn('platform_id', $scope_ids)
                ->distinct()
                ->pluck('company_id')
                ->toArray();
            $query->whereIn('id', $company_ids);
        }
        // 'all' → 不附加条件

        // 按 name 模糊搜索
        $name = $this->request->input('name');
        if ($name !== null && $name !== '') {
            $query->where(function ($q) use ($name): void {
                $q->where('name', 'ilike', "%{$name}%")
                    ->orWhere('label', 'ilike', "%{$name}%");
            });
        }

        $companies = $query->orderBy('id')->get();

        return [
            'code' => 0,
            'message' => '获取成功',
            'data' => $companies,
        ];
    }
}
