<?php

namespace Database\Seeders;

use App\Models\KodeAksesKantor;
use App\Models\UnitKerja;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class KodeAksesKantorSeeder extends Seeder
{
    public function run(): void
    {
        $superAdmin = User::where('role', 'super_admin')->firstOrFail();

        UnitKerja::orderBy('id')->get()->each(function (UnitKerja $unit) use ($superAdmin) {
            $suffix = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', Str::ascii($unit->nama_unit)), 0, 8));
            $code = 'SKB-' . str_pad($suffix, 4, 'X') . '-' . str_pad((string) $unit->id, 3, '0', STR_PAD_LEFT);

            $kodeAkses = KodeAksesKantor::firstOrCreate(
                ['kode' => $code],
                [
                    'unit_kerja_id' => $unit->id,
                    'created_by' => $superAdmin->id,
                    'batas_penggunaan' => 100,
                    'jumlah_digunakan' => 0,
                    'kedaluwarsa_pada' => now()->addYear(),
                    'aktif' => true,
                ]
            );

            $kodeAkses->update([
                'unit_kerja_id' => $unit->id,
                'created_by' => $superAdmin->id,
                'batas_penggunaan' => max(100, $kodeAkses->batas_penggunaan),
            ]);
        });
    }
}
