<?php

namespace App\Jobs;

use App\Invitation;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
use App\Mail\InviteExpiringSoon;

class ExpiredInviteCleanup implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        // 1. Notify invites expiring within the next 24 hours that haven't been notified yet
        Invitation::where('status', 'pending')
            ->where('notified', false)
            ->whereBetween('expiration', [Carbon::now(), Carbon::now()->addDay()])
            ->chunkById(100, function ($invites) {
                foreach ($invites as $invite) {
                    Mail::to($invite->requestor_email)
                        ->send(new InviteExpiringSoon($invite));

                    $invite->notified = true;
                    $invite->save();
                }
            });

        // 2. Delete invites that have actually expired
        Invitation::where('status', 'pending')
            ->where('expiration', '<', Carbon::now())
            ->chunkById(100, function ($invites) {
                foreach ($invites as $invite) {
                    $invite->delete();
                }
            });
    }
}
