<?php

namespace App\Http\Controllers;

use App\Models\ExportToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class UserExportController extends Controller
{
    public function premiumExportRequest(Request $request)
    {
        $user = Auth::user();
        $user->load('user_usage');

        if ($user->user_usage->non_watermark_videos_left <= 0) {
            return response()->json([
                'error' => [
                    'message' => 'You have no credits left to export.',
                ],
            ]);
        }

        // Immediately consume the credit and create token
        $user->user_usage->update([
            'non_watermark_videos_left' => $user->user_usage->non_watermark_videos_left - 1,
        ]);

        // Create export token (expires in 30 minutes)
        $token = ExportToken::create([
            'user_id' => $user->id,
            'token' => Str::uuid()->toString(),
            'is_premium' => true,
            'credits_reserved' => 1,
            'expires_at' => now()->addMinutes(30),
        ]);

        $user->user_usage->refresh();

        return response()->json([
            'success' => [
                'data' => [
                    'user_usage' => $user->user_usage,
                    'export_token' => $token->token,
                ],
            ],
        ]);
    }

    public function premiumExportComplete(Request $request)
    {
        $request->validate([
            'export_token' => 'required|string',
        ]);

        $user = Auth::user();
        $user->load('user_usage');

        // Find the token
        $token = ExportToken::where('token', $request->export_token)
            ->where('user_id', $user->id)
            ->first();

        if (! $token) {
            return response()->json([
                'error' => [
                    'message' => 'Invalid export token.',
                ],
            ]);
        }

        if (! $token->isValid()) {
            return response()->json([
                'error' => [
                    'message' => 'Export token has expired or already been used.',
                ],
            ]);
        }

        // Mark token as used
        $token->markAsUsed();

        return response()->json([
            'success' => [
                'data' => [
                    'user_usage' => $user->user_usage,
                ],
            ],
        ]);
    }
}
