<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\DirectBookingRequest;
use Illuminate\Support\Facades\Log;

class ProcessExpiredBookingRequests extends Command
{
    protected $signature = 'booking:process-expired';
    protected $description = 'Process expired booking requests and update their status';

    public function handle()
    {
        Log::info('🔄 PROCESS EXPIRED REQUESTS - Starting');

        $expiredCount = 0;
        $failedCount = 0;

        try {
            DirectBookingRequest::expired()
                ->with(['parent', 'babysitter'])
                ->chunk(100, function ($requests) use (&$expiredCount, &$failedCount) {
                    foreach ($requests as $request) {
                        try {
                            if ($request->shouldAutoExpire()) {
                                $request->expire();
                                $expiredCount++;

                                Log::info('✅ AUTO EXPIRE - Success:', [
                                    'booking_request_id' => $request->booking_request_id,
                                    'parent_id' => $request->parent_id,
                                    'babysitter_id' => $request->babysitter_id
                                ]);
                            }
                        } catch (\Exception $e) {
                            $failedCount++;
                            Log::error('❌ AUTO EXPIRE - Failed:', [
                                'booking_request_id' => $request->booking_request_id,
                                'error' => $e->getMessage()
                            ]);
                        }
                    }
                });

            Log::info('🎯 PROCESS EXPIRED REQUESTS - Completed', [
                'expired_count' => $expiredCount,
                'failed_count' => $failedCount
            ]);

            $this->info("Successfully processed {$expiredCount} expired requests. Failed: {$failedCount}");

        } catch (\Exception $e) {
            Log::error('❌ PROCESS EXPIRED REQUESTS - Command failed:', [
                'error' => $e->getMessage()
            ]);
            $this->error('Command failed: ' . $e->getMessage());
            return 1;
        }

        return 0;
    }
}
