<?php

namespace Database\Seeders\Simulation;

use App\Models\AccountingEntry;
use App\Models\FinancialAccount;
use App\Models\FinancialAccountTransaction;
use Carbon\CarbonImmutable;
use Illuminate\Database\Seeder;

class SimulationOpeningLedgerSeeder extends Seeder
{
    public function run(): void
    {
        $date = CarbonImmutable::parse((string) config('simulation.anchor_date', '2026-08-01'))
            ->subMonths(7)
            ->startOfDay();

        FinancialAccount::query()
            ->where('name', 'like', 'SIM %')
            ->orderBy('id')
            ->get()
            ->each(function (FinancialAccount $account) use ($date): void {
                $opening = number_format((float) $account->opening_balance, 2, '.', '');
                if ((float) $opening <= 0) return;

                $reference = 'SIM-OPEN-'.$account->id;
                $description = 'Simulation opening balance for '.$account->name;

                FinancialAccountTransaction::query()->firstOrCreate(
                    ['account_id'=>$account->id,'type'=>'opening_balance','reference'=>$reference],
                    [
                        'transaction_number'=>$reference,
                        'branch_id'=>$account->branch_id,
                        'transaction_date'=>$date,
                        'description'=>$description,
                        'money_in'=>$opening,
                        'money_out'=>'0.00',
                        'running_balance'=>$opening,
                        'user_id'=>$account->created_by,
                        'related_type'=>FinancialAccount::class,
                        'related_id'=>$account->id,
                    ],
                );

                $journal = 'JRN-'.$reference;
                AccountingEntry::query()->firstOrCreate(
                    ['journal_number'=>$journal,'category'=>'assets','related_type'=>FinancialAccount::class,'related_id'=>$account->id],
                    [
                        'branch_id'=>$account->branch_id,'financial_account_id'=>$account->id,'entry_date'=>$date,
                        'reference'=>$reference,'event_type'=>'opening_balance','description'=>$description,
                        'debit'=>$opening,'credit'=>'0.00','user_id'=>$account->created_by,
                    ],
                );
                AccountingEntry::query()->firstOrCreate(
                    ['journal_number'=>$journal,'category'=>'capital','related_type'=>FinancialAccount::class,'related_id'=>$account->id],
                    [
                        'branch_id'=>$account->branch_id,'financial_account_id'=>null,'entry_date'=>$date,
                        'reference'=>$reference,'event_type'=>'opening_balance','description'=>$description,
                        'debit'=>'0.00','credit'=>$opening,'user_id'=>$account->created_by,
                    ],
                );
            });
    }
}
