<?php

namespace App\Console\Commands;

use App\Models\EventPhotoboothSetting;
use App\Services\Photobooth\PhotoboothProvisioner;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class DeactivateExpiredPhotoboothAccounts extends Command
{
    protected $signature = 'photobooth:cleanup-expired';

    protected $description = 'Disable Photobooth FTP accounts that have passed their expiry date.';

    public function handle(PhotoboothProvisioner $provisioner): int
    {
        $total = 0;

        EventPhotoboothSetting::query()
            ->where('enabled', true)
            ->where('mode', 'ftp')
            ->whereNotNull('expires_at')
            ->where('expires_at', '<=', now())
            ->with('event')
            ->chunkById(50, function ($settings) use (&$total, $provisioner) {
                foreach ($settings as $setting) {
                    $event = $setting->event;

                    if (! $event) {
                        continue;
                    }

                    try {
                        $provisioner->disable($event);
                        $total++;
                    } catch (\Throwable $exception) {
                        Log::error('Failed to disable expired photobooth account', [
                            'event_id' => $event->id,
                            'message' => $exception->getMessage(),
                        ]);
                    }
                }
            });

        $this->info(sprintf('Photobooth cleanup complete (%d accounts disabled).', $total));

        return self::SUCCESS;
    }
}
