<?php

namespace Database\Seeders;

use App\Domain\Financial\Enums\AllocationType;
use App\Domain\Financial\Enums\RevenueSource;
use App\Domain\Financial\Enums\TaxMode;
use App\Domain\Financial\Models\FinancialAccount;
use App\Domain\Financial\Models\RevenueMapping;
use App\Domain\Shared\Models\Academy;
use Illuminate\Database\Seeder;

/**
 * A starting routing rule per revenue source, for every academy.
 *
 * Each one reproduces exactly what the system did before revenue routing
 * existed — the account the old hardcoded `match` would have chosen, no tax —
 * so installing this changes where nothing lands. What it gives a new tenant is
 * a screen that shows the truth about its own books on day one, instead of nine
 * rows saying "not configured".
 *
 * The install migration does the same for tenants that already exist. This
 * covers the fresh-database case, where `academies` is still empty while
 * migrations run. Both are idempotent, and neither overwrites a rule an
 * accountant has since edited.
 */
class RevenueRoutingSeeder extends Seeder
{
    /** Sources that ship switched off; see the migration for why. */
    private const INACTIVE = [RevenueSource::ServiceFee->value];

    public function run(): void
    {
        $academies = Academy::withoutGlobalScopes()->get();

        if ($academies->isEmpty()) {
            $this->command?->warn('No academy exists yet — skipping revenue routing seeder.');

            return;
        }

        $created = 0;

        foreach ($academies as $academy) {
            $accounts = FinancialAccount::withoutGlobalScopes()
                ->where('academy_id', $academy->id)
                ->pluck('id', 'code');

            foreach (RevenueSource::catalogue() as $source) {
                $accountId = $accounts[$source->legacyAccountCode()] ?? null;

                if (! $accountId) {
                    continue;
                }

                $exists = RevenueMapping::withoutGlobalScopes()
                    ->where('academy_id', $academy->id)
                    ->where('source_key', $source->value)
                    ->whereNull('scope_type')
                    ->exists();

                if ($exists) {
                    continue;
                }

                $mapping = RevenueMapping::withoutGlobalScopes()->create([
                    'academy_id' => $academy->id,
                    'source_key' => $source->value,
                    'label' => $source->label(),
                    'is_active' => ! in_array($source->value, self::INACTIVE, true),
                    'tax_mode' => TaxMode::None->value,
                    'tax_rate_bp' => 0,
                ]);

                $mapping->lines()->create([
                    'academy_id' => $academy->id,
                    'account_id' => $accountId,
                    'allocation_type' => AllocationType::Remainder->value,
                    'sort_order' => 0,
                ]);

                $created++;
            }
        }

        $this->command?->info("Seeded {$created} revenue routing rules.");
    }
}
