<?php

namespace App\Console\Commands;

use App\Models\Association;
use App\Services\FinancialManagementService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ApplyLateFees extends Command
{
    protected $signature = 'financial:apply-late-fees
                            {--association= : Process only a specific association ID}';

    protected $description = 'Apply late fees to overdue assignments for associations with auto_apply_late_fees enabled';

    public function handle(FinancialManagementService $service): int
    {
        $this->info('Processing late fee applications...');
        $this->newLine();

        $query = Association::where('auto_apply_late_fees', true);

        if ($associationId = $this->option('association')) {
            $query->where('id', $associationId);
        }

        $associations = $query->get();

        if ($associations->isEmpty()) {
            $this->info('No associations have auto_apply_late_fees enabled.');
            return self::SUCCESS;
        }

        $totalApplied = 0;

        foreach ($associations as $association) {
            try {
                $count = $service->applyLateFees($association);

                if ($count > 0) {
                    $this->line("  <info>{$association->name}</info>: Applied {$count} late fee(s)");
                    $totalApplied += $count;
                }
            } catch (\Throwable $e) {
                $this->error("  {$association->name}: Failed - {$e->getMessage()}");
                Log::error('Late fee application failed for association', [
                    'association_id' => $association->id,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        $this->newLine();
        $this->info("Total late fees applied: {$totalApplied}");

        return self::SUCCESS;
    }
}
