<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Mtc\MercuryDataModels\PreviewToken;

class PreviewTokenController extends Controller
{
    /**
     * Generate a preview token for a page.
     */
    public function store(Request $request, int $pageId): JsonResponse
    {
        $request->validate([
            'version_id' => 'nullable|integer',
        ]);

        // Clean up expired tokens for this page
        PreviewToken::cleanupExpired($pageId);

        $token = PreviewToken::create([
            'page_id' => $pageId,
            'version_id' => $request->input('version_id'),
            'created_by' => Auth::id(),
        ]);

        return response()->json([
            'token' => $token->token,
            'expires_at' => $token->expires_at->toISOString(),
        ]);
    }
}
