<?php

namespace App\Representation\Controller;

use App\Representation\Service\DomainContextResolver;
use App\Shared\Controller\BaseController;
use OpenApi\Attributes as OA;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

/**
 * زمینه‌ی عمومی یک دامنه برای سایت nobat724: شهر است، دامنه‌ی اختصاصی نماینده است، یا ناشناخته.
 * سایت عمومی برای دامنه‌های خارج از data/city.json از این endpoint استفاده می‌کند.
 */
#[OA\Tag(name: 'Representations')]
class SiteContextController extends BaseController
{
    public function __construct(
        private readonly DomainContextResolver $resolver,
    ) {}

    #[OA\Get(
        path: '/api/v1/site-context',
        summary: 'Resolve a domain to its site context (city | representation | unknown)',
        parameters: [
            new OA\Parameter(name: 'domain', in: 'query', required: true, schema: new OA\Schema(type: 'string')),
        ],
        responses: [
            new OA\Response(response: 200, description: 'Domain context'),
        ]
    )]
    #[Route('/api/v1/site-context', methods: ['GET'])]
    public function resolve(Request $request): JsonResponse
    {
        $ctx = $this->resolver->resolve((string) $request->query->get('domain', ''));

        $type = 'unknown';
        if ($ctx->city !== null) {
            $type = 'city';
        } elseif ($ctx->representation !== null) {
            $type = 'representation';
        }

        return $this->success([
            'type'           => $type,
            'city'           => $ctx->city === null ? null : [
                'id'   => $ctx->city->getId(),
                'name' => $ctx->city->getName(),
            ],
            'representation' => $ctx->representation === null ? null : [
                'uuid'      => $ctx->representation->getUuid(),
                'full_name' => $ctx->representation->getFullName(),
                'is_global' => $ctx->representation->isGlobal(),
            ],
        ]);
    }
}
