<?php

use App\Domain\Financial\Models\FinancialAccount;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * The chart of accounts is a record every client needs, not client-specific
 * content, so it belongs in a migration exactly as schema does.
 *
 * FinancialAccountsSeeder only ever seeded `Academy::first()`, and db:seed only
 * runs when RUN_SEED_ON_FIRST_DEPLOY=true — so any academy created after the
 * first one has no chart at all, and accounts added to the seeder after a
 * tenant was installed never reached it. On the verified oc_sport copy, 4060
 * (External Revenue) is in the seeder and missing from the database.
 *
 * PaymentService now resolves accounts by code and hard-fails when one is
 * absent, so this has to land before it: a missing account would turn every
 * payment into a DomainException at the till.
 */
return new class extends Migration
{
    private const ACCOUNTS = [
        // Assets
        ['code' => '1000', 'name' => 'Cash', 'name_ar' => 'النقدية', 'type' => 'asset', 'category' => 'current_asset'],
        ['code' => '1010', 'name' => 'Bank Account', 'name_ar' => 'الحساب البنكي', 'type' => 'asset', 'category' => 'current_asset'],
        ['code' => '1100', 'name' => 'Accounts Receivable', 'name_ar' => 'المدينون', 'type' => 'asset', 'category' => 'current_asset'],
        ['code' => '1200', 'name' => 'Wallets Receivable', 'name_ar' => 'أرصدة المحافظ', 'type' => 'asset', 'category' => 'current_asset'],

        // Revenue
        ['code' => '4000', 'name' => 'Training Revenue', 'name_ar' => 'إيرادات التدريب', 'type' => 'revenue', 'category' => 'operating'],
        ['code' => '4010', 'name' => 'Registration Fees', 'name_ar' => 'رسوم التسجيل', 'type' => 'revenue', 'category' => 'operating'],
        ['code' => '4020', 'name' => 'Equipment Sales', 'name_ar' => 'مبيعات المعدات', 'type' => 'revenue', 'category' => 'operating'],
        ['code' => '4030', 'name' => 'Facility Rental', 'name_ar' => 'إيجار الملاعب', 'type' => 'revenue', 'category' => 'operating'],
        ['code' => '4040', 'name' => 'Private Sessions', 'name_ar' => 'الحصص الخاصة', 'type' => 'revenue', 'category' => 'operating'],
        ['code' => '4050', 'name' => 'Tournament Fees', 'name_ar' => 'رسوم البطولات', 'type' => 'revenue', 'category' => 'operating'],
        ['code' => '4060', 'name' => 'External Revenue', 'name_ar' => 'إيرادات خارجية', 'type' => 'revenue', 'category' => 'operating'],

        // Expenses
        ['code' => '5000', 'name' => 'Trainer Salaries', 'name_ar' => 'رواتب المدربين', 'type' => 'expense', 'category' => 'operating'],
        ['code' => '5010', 'name' => 'Facility Rent', 'name_ar' => 'إيجار المنشآت', 'type' => 'expense', 'category' => 'operating'],
        ['code' => '5020', 'name' => 'Equipment Purchases', 'name_ar' => 'مشتريات المعدات', 'type' => 'expense', 'category' => 'operating'],
        ['code' => '5030', 'name' => 'Utilities', 'name_ar' => 'المرافق', 'type' => 'expense', 'category' => 'operating'],
        ['code' => '5040', 'name' => 'Marketing', 'name_ar' => 'التسويق', 'type' => 'expense', 'category' => 'operating'],
        ['code' => '5050', 'name' => 'Miscellaneous Expenses', 'name_ar' => 'مصروفات نثرية', 'type' => 'expense', 'category' => 'operating'],

        // Liability
        ['code' => '2000', 'name' => 'Accounts Payable', 'name_ar' => 'الدائنون', 'type' => 'liability', 'category' => 'current_liability'],
        ['code' => '2010', 'name' => 'Unearned Revenue', 'name_ar' => 'إيرادات مقدمة', 'type' => 'liability', 'category' => 'current_liability'],
        ['code' => '2020', 'name' => 'Refunds Payable', 'name_ar' => 'مستردات مستحقة', 'type' => 'liability', 'category' => 'current_liability'],
    ];

    public function up(): void
    {
        if (! Schema::hasTable('financial_accounts') || ! Schema::hasTable('academies')) {
            return;
        }

        $academyIds = DB::table('academies')->pluck('id');

        foreach ($academyIds as $academyId) {
            foreach (self::ACCOUNTS as $account) {
                FinancialAccount::withoutGlobalScopes()->firstOrCreate(
                    ['academy_id' => $academyId, 'code' => $account['code']],
                    $account + ['academy_id' => $academyId, 'is_system' => true, 'is_active' => true]
                );
            }
        }
    }

    public function down(): void
    {
        // Deliberately empty: these are system accounts that live transactions
        // reference by id. Removing them would orphan the ledger.
    }
};
