<?php

namespace App\Console\Commands;

use App\Models\ExportToken;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CleanupExpiredExportTokens extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cleanup:expired-export-tokens';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cleanup expired export tokens and restore credits to users';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting cleanup of expired export tokens...');

        // Get all expired and unused tokens
        $expiredTokens = ExportToken::expiredAndUnused()->get();

        if ($expiredTokens->isEmpty()) {
            $this->info('No expired tokens found.');

            return;
        }

        $this->info('Found '.$expiredTokens->count().' expired tokens to process.');

        $restoredCredits = 0;

        DB::transaction(function () use ($expiredTokens, &$restoredCredits) {
            foreach ($expiredTokens as $token) {
                if ($token->is_premium && $token->credits_reserved > 0) {
                    // Restore credits to user
                    $token->user->user_usage()->increment('non_watermark_videos_left', $token->credits_reserved);
                    $restoredCredits += $token->credits_reserved;

                    $this->info("Restored {$token->credits_reserved} credits to user {$token->user_id}");
                }

                // Delete the expired token
                $token->delete();
            }
        });

        $this->info("Cleanup completed. Restored {$restoredCredits} credits and deleted {$expiredTokens->count()} expired tokens.");
    }
}
