<?php

namespace App\Console\Commands;

use App\Models\Invitation;
use Illuminate\Console\Command;
use Carbon\Carbon;

class CleanupExpiredInvitations extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invitations:cleanup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Mark expired invitations as expired and clean up old data';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $this->info('Starting invitation cleanup...');

        // Mark expired invitations
        $expiredCount = Invitation::where('status', 'pending')
            ->where('expires_at', '<', Carbon::now())
            ->update(['status' => 'expired']);

        $this->info("Marked {$expiredCount} invitations as expired.");

        // Optionally delete very old invitations (older than 30 days)
        $deletedCount = Invitation::where('status', '!=', 'pending')
            ->where('created_at', '<', Carbon::now()->subDays(30))
            ->delete();

        $this->info("Deleted {$deletedCount} old invitations.");

        $this->info('Invitation cleanup completed successfully.');

        return Command::SUCCESS;
    }
}
