<?php

namespace App\Http\Controllers;

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

class UserExportController extends Controller
{
    public function premiumExportRequest(Request $request)
    {
        $request->validate([
            'meme_media_ids' => 'nullable|string', // Accept hashid string
            'background_media_ids' => 'nullable|string', // Accept hashid string
            'caption_texts' => 'required|array',
            'caption_texts.*' => 'string',
        ]);

        // Convert hashids to actual database IDs
        $memeMediaId = $request->meme_media_ids ? hashids_decode($request->meme_media_ids) : null;
        $backgroundMediaId = $request->background_media_ids ? hashids_decode($request->background_media_ids) : null;

        $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,
            'metadata' => [
                'meme_media_id' => $memeMediaId,
                'background_media_id' => $backgroundMediaId,
                'caption_texts' => $request->caption_texts,
            ],
            'expires_at' => now()->addMinutes(30),
        ]);

        // Track the export
        try {
            $trackingService = app(TrackingAnalyticsService::class);
            $trackingService->trackExport(null, $memeMediaId, $backgroundMediaId, $request->caption_texts);
        } catch (\Exception $e) {
            // Silently ignore tracking errors
        }

        $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,
                ],
            ],
        ]);
    }

    public function basicExportRequest(Request $request)
    {
        $request->validate([
            'meme_media_ids' => 'nullable|string', // Accept hashid string
            'background_media_ids' => 'nullable|string', // Accept hashid string
            'caption_texts' => 'required|array',
            'caption_texts.*' => 'string',
        ]);

        // Convert hashids to actual database IDs
        $memeMediaId = $request->meme_media_ids ? hashids_decode($request->meme_media_ids) : null;
        $backgroundMediaId = $request->background_media_ids ? hashids_decode($request->background_media_ids) : null;

        // No authentication required for basic exports
        // Create export token (expires in 30 minutes)
        $token = ExportToken::create([
            'user_id' => null, // Anonymous user
            'token' => Str::uuid()->toString(),
            'is_premium' => false,
            'credits_reserved' => 0, // No credits for basic exports
            'expires_at' => now()->addMinutes(30),
            'metadata' => [
                'meme_media_id' => $memeMediaId,
                'background_media_id' => $backgroundMediaId,
                'caption_texts' => $request->caption_texts,
            ],
        ]);

        // Track the export
        try {
            $trackingService = app(TrackingAnalyticsService::class);
            $trackingService->trackExport(null, $memeMediaId, $backgroundMediaId, $request->caption_texts);
        } catch (\Exception $e) {
            // Silently ignore tracking errors
        }

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

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

        // Find the token (no user requirement)
        $token = ExportToken::where('token', $request->export_token)
            ->whereNull('user_id') // Only anonymous tokens
            ->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' => [
                    'message' => 'Export completed successfully.',
                ],
            ],
        ]);
    }
}
