<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\NovaCards;

use App\Http\Controllers\Controller;
use App\Models\NovaCard;
use App\Models\NovaCardExport;
use App\Services\NovaCards\NovaCardExportService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class NovaCardExportController extends Controller
{
    public function __construct(
        private readonly NovaCardExportService $exports,
    ) {
    }

    /**
     * Request an export for the given card.
     *
     * POST /api/cards/{id}/export
     */
    public function store(Request $request, int $id): JsonResponse
    {
        $card = NovaCard::query()
            ->where(function ($q) use ($request): void {
                // Owner can export any status; others can only export published cards.
                $q->where('user_id', $request->user()->id)
                    ->orWhere(function ($inner) use ($request): void {
                        $inner->where('status', NovaCard::STATUS_PUBLISHED)
                              ->where('visibility', NovaCard::VISIBILITY_PUBLIC)
                              ->where('allow_export', true);
                    });
            })
            ->findOrFail($id);

        $data = $request->validate([
            'export_type' => ['required', 'string', 'in:' . implode(',', array_keys(NovaCardExportService::EXPORT_SPECS))],
            'options' => ['sometimes', 'array'],
        ]);

        $export = $this->exports->requestExport(
            $request->user(),
            $card,
            $data['export_type'],
            (array) ($data['options'] ?? []),
        );

        return response()->json([
            'data' => $this->exports->getStatus($export),
        ], $export->wasRecentlyCreated ? Response::HTTP_ACCEPTED : Response::HTTP_OK);
    }

    /**
     * Poll export status.
     *
     * GET /api/cards/exports/{exportId}
     */
    public function show(Request $request, int $exportId): JsonResponse
    {
        $export = NovaCardExport::query()
            ->where('user_id', $request->user()->id)
            ->findOrFail($exportId);

        return response()->json([
            'data' => $this->exports->getStatus($export),
        ]);
    }
}
