<?php

namespace App\Console\Commands;

use App\Models\Giveaway;
use App\Models\Admin;
use App\Traits\NotificationTrait;
use App\Mail\NewNotification;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class SelectGiveawayWinners extends Command
{
    use NotificationTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'giveaway:select-winners';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Auto-close ended giveaways and select winners for those without one';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Step 1: Mark active giveaways that have passed their end date as "ended"
        $toClose = Giveaway::where('status', 'active')
            ->where('ends_at', '<=', now())
            ->get();

        foreach ($toClose as $giveaway) {
            $giveaway->update(['status' => 'ended']);
            $this->info("Closed giveaway: {$giveaway->title}");
        }

        // Step 2: Select winners for ended giveaways that have entries but no winner
        $needsWinner = Giveaway::where('status', 'ended')
            ->whereDoesntHave('winner')
            ->whereHas('entries')
            ->get();

        foreach ($needsWinner as $giveaway) {
            try {
                $winner = $giveaway->selectWinner();

                if ($winner) {
                    $this->info("Winner selected for '{$giveaway->title}': User #{$winner->user_id}");

                    // Send email to winner
                    $user = $winner->user;
                    if ($user) {
                        try {
                            $body = "Congratulations! You have been selected as the winner of the giveaway: <strong>{$giveaway->title}</strong>.<br><br>"
                                . "Prize: \${$giveaway->prize_value}<br>"
                                . "Our team will contact you about claiming your prize.";

                            Mail::to($user->email)->send(new NewNotification(
                                $body,
                                "🎉 You Won: {$giveaway->title}",
                                $user->name
                            ));
                        } catch (\Exception $e) {
                            Log::warning("Failed to email giveaway winner: " . $e->getMessage());
                        }

                        // In-app notification
                        $this->sendDirectUserNotification(
                            $user->id,
                            '🎉 You Won a Giveaway!',
                            "Congratulations! You won: {$giveaway->title} — Prize value: \${$giveaway->prize_value}",
                            'success',
                            $giveaway->id,
                            'giveaway'
                        );
                    }

                    // Notify admins
                    $admins = Admin::all();
                    foreach ($admins as $admin) {
                        $this->sendDirectAdminNotification(
                            $admin->id,
                            'Giveaway Winner Selected',
                            "Auto-selected winner for '{$giveaway->title}': {$user->name} (#{$user->id})",
                            'info',
                            $giveaway->id,
                            'giveaway'
                        );
                    }
                } else {
                    $this->warn("Could not select winner for '{$giveaway->title}'");
                }
            } catch (\Exception $e) {
                $this->error("Error selecting winner for '{$giveaway->title}': {$e->getMessage()}");
                Log::error("Giveaway winner selection failed", [
                    'giveaway_id' => $giveaway->id,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        $this->info("Giveaway processing complete. Closed: {$toClose->count()}, Winners: {$needsWinner->count()}");

        return 0;
    }
}
