<?php

namespace Database\Seeders;

use App\Models\Activity;
use App\Models\Audit;
use App\Models\AuditResponse;
use App\Models\CashRecord;
use App\Models\User;
use Illuminate\Database\Seeder;

class AuditSeeder extends Seeder
{
    public function run(): void
    {
        $auditor  = User::role('auditor')->first();
        $ketua    = User::role('ketua')->first();
        $kas      = CashRecord::first();
        $kegiatan = Activity::where('status', 'approved')->first();

        $audits = [
            [
                'model'       => $kas,
                'issue_type'  => 'warning',
                'description' => 'Transaksi tidak disertai bukti kwitansi yang memadai. Mohon dilampirkan dokumen pendukung.',
                'status'      => 'resolved',
                'response'    => 'Kwitansi sudah dilampirkan dan disimpan di sekretariat.',
            ],
            [
                'model'       => $kegiatan,
                'issue_type'  => 'warning',
                'description' => 'Laporan pelaksanaan kegiatan belum mencantumkan daftar hadir peserta secara lengkap.',
                'status'      => 'open',
                'response'    => null,
            ],
            [
                'model'       => $kas ? CashRecord::skip(1)->first() ?? $kas : null,
                'issue_type'  => 'critical',
                'description' => 'Ditemukan selisih antara catatan kas dengan laporan keuangan bulan lalu sebesar Rp 50.000. Perlu klarifikasi segera.',
                'status'      => 'open',
                'response'    => null,
            ],
        ];

        foreach ($audits as $data) {
            if (! $data['model']) continue;

            $audit = Audit::create([
                'auditor_id'  => $auditor->id,
                'model_type'  => get_class($data['model']),
                'model_id'    => $data['model']->id,
                'issue_type'  => $data['issue_type'],
                'description' => $data['description'],
                'status'      => $data['status'],
            ]);

            if ($data['response']) {
                AuditResponse::create([
                    'audit_id'     => $audit->id,
                    'responded_by' => $ketua->id,
                    'response_text' => $data['response'],
                ]);
            }
        }
    }
}
