<?php

namespace Database\Seeders;

use App\Models\Approval;
use App\Models\CashCategory;
use App\Models\CashRecord;
use App\Models\User;
use Illuminate\Database\Seeder;

class CashSeeder extends Seeder
{
    public function run(): void
    {
        $pemasukan  = CashCategory::firstOrCreate(['name' => 'Iuran & Donasi'],  ['type' => 'pemasukan']);
        $pengeluaran = CashCategory::firstOrCreate(['name' => 'Operasional'], ['type' => 'pengeluaran']);

        $bendahara = User::role('bendahara')->first();
        $ketua     = User::role('ketua')->first();

        $records = [
            ['category_id' => $pemasukan->id,   'amount' => 500000,  'description' => 'Iuran anggota bulan Januari', 'date' => now()->subMonths(2)],
            ['category_id' => $pemasukan->id,   'amount' => 500000,  'description' => 'Iuran anggota bulan Februari', 'date' => now()->subMonth()],
            ['category_id' => $pemasukan->id,   'amount' => 1000000, 'description' => 'Donasi kegiatan kerja bakti', 'date' => now()->subDays(20)],
            ['category_id' => $pengeluaran->id, 'amount' => 250000,  'description' => 'Pembelian alat kebersihan', 'date' => now()->subDays(18)],
            ['category_id' => $pengeluaran->id, 'amount' => 150000,  'description' => 'Konsumsi rapat bulanan', 'date' => now()->subDays(5)],
        ];

        foreach ($records as $data) {
            $amount = $data['amount'];

            // 500rb–2jt: butuh approval ketua, belum verified
            if ($amount >= 500_000 && $amount <= 2_000_000) {
                $record = CashRecord::create(array_merge($data, [
                    'created_by'  => $bendahara?->id,
                    'verified_by' => null,
                    'verified_at' => null,
                ]));

                Approval::create([
                    'model_type'         => CashRecord::class,
                    'model_id'           => $record->id,
                    'required_approvals' => 1,
                    'status'             => 'pending',
                ]);
            } else {
                // < 500rb: langsung verified
                CashRecord::create(array_merge($data, [
                    'created_by'  => $bendahara?->id,
                    'verified_by' => $ketua?->id,
                    'verified_at' => now()->subDays(1),
                ]));
            }
        }
    }
}
