<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Preview\StorePreviewRequest;
use App\Models\Page;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use OpenApi\Attributes as OA;

class PreviewController extends Controller
{
    private const CACHE_TTL = 600; // 10 minutes

    #[OA\Post(
        path: '/api/admin/preview',
        summary: 'Önizleme oluştur',
        tags: ['Admin - Preview'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(required: true, content: new OA\JsonContent(
            required: ['page_id', 'blocks'],
            properties: [
                new OA\Property(property: 'page_id', type: 'integer'),
                new OA\Property(property: 'blocks', type: 'array', items: new OA\Items(
                    properties: [
                        new OA\Property(property: 'type', type: 'string'),
                        new OA\Property(property: 'content', type: 'object'),
                        new OA\Property(property: 'order_index', type: 'integer'),
                    ],
                )),
            ],
        )),
        responses: [
            new OA\Response(response: 201, description: 'Önizleme oluşturuldu'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function store(StorePreviewRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $page = Page::findOrFail($validated['page_id']);
        $token = (string) Str::uuid();

        $blocks = collect($validated['blocks'])
            ->sortBy('order_index')
            ->values()
            ->map(fn (array $block, int $index) => [
                'id' => $index + 1,
                'type' => $block['type'],
                'content' => $block['content'],
                'order_index' => $block['order_index'],
            ])
            ->all();

        Cache::put("preview_{$token}", [
            'id' => $page->id,
            'slug' => $page->slug,
            'title' => $page->title,
            'meta_title' => $page->meta_title,
            'meta_description' => $page->meta_description,
            'is_active' => $page->is_active,
            'blocks' => $blocks,
            'created_at' => $page->created_at?->toISOString(),
            'updated_at' => now()->toISOString(),
        ], self::CACHE_TTL);

        $previewUrl = config('app.frontend_url')."/api/preview?token={$token}&slug={$page->slug}";

        return response()->json([
            'token' => $token,
            'preview_url' => $previewUrl,
            'expires_in' => self::CACHE_TTL,
        ], 201);
    }

    #[OA\Delete(
        path: '/api/admin/preview/{token}',
        summary: 'Önizlemeyi sil',
        tags: ['Admin - Preview'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'token', in: 'path', required: true, schema: new OA\Schema(type: 'string'))],
        responses: [new OA\Response(response: 200, description: 'Önizleme silindi')],
    )]
    public function destroy(string $token): JsonResponse
    {
        Cache::forget("preview_{$token}");

        return response()->json(['message' => 'Önizleme silindi.']);
    }
}
