<?php

declare(strict_types=1);

namespace App\Application\SmartLink\Api;

use App\Domain\SmartLink\Enums\LinkType;
use App\Domain\SmartLink\Services\SmartLinkService;
use App\Domain\SmartLink\ValueObjects\LinkTitle;
use App\Framework\Attributes\Route;
use App\Framework\Http\HttpRequest;
use App\Framework\Http\Method;
use App\Framework\Http\Status;
use App\Framework\Router\Result\JsonResult;

final readonly class CreateSmartLink
{
    public function __construct(
        private SmartLinkService $smartLinkService
    ) {
    }

    #[Route(path: '/api/smart-links', method: Method::POST)]
    public function __invoke(HttpRequest $request): JsonResult
    {
        $data = $request->parsedBody->toArray();

        // Workaround: If parsedBody is empty, try parsing JSON directly
        if (empty($data)) {
            $rawBody = file_get_contents('php://input');
            $data = json_decode($rawBody, true) ?? [];
        }

        if (! isset($data['type']) || ! isset($data['title'])) {
            return new JsonResult([
                'error' => 'Missing required fields: type and title',
            ], Status::BAD_REQUEST);
        }

        $type = LinkType::from($data['type'] ?? '');
        $title = LinkTitle::fromString($data['title'] ?? '');

        $smartLink = $this->smartLinkService->createLink(
            type: $type,
            title: $title,
            userId: $data['user_id'] ?? null,
            coverImageUrl: $data['cover_image_url'] ?? null
        );

        return new JsonResult([
            'id' => $smartLink->id->toString(),
            'short_code' => $smartLink->shortCode->toString(),
            'type' => $smartLink->type->value,
            'title' => $smartLink->title->toString(),
            'status' => $smartLink->status->value,
            'created_at' => $smartLink->createdAt->format('Y-m-d H:i:s'),
        ], Status::CREATED);
    }
}
