<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class PermissionSeeder extends Seeder
{
    public function run(): void
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        $ketua = Role::findByName('ketua');
        $bendahara = Role::findByName('bendahara');
        $pengurus = Role::findByName('pengurus');
        $anggota = Role::findByName('anggota');
        $auditor = Role::findByName('auditor');

        // Ketua: akses penuh kecuali shield roles
        $ketua->syncPermissions(Permission::where('name', 'not like', '%Role%')
            ->where('name', 'not like', '%Permission%')
            ->get());

        // Bendahara: hanya kas + iuran + artikel sendiri
        $bendahara->syncPermissions(Permission::where('name', 'like', '%CashRecord%')
            ->orWhere('name', 'like', '%CashCategory%')
            ->orWhere('name', 'like', '%MemberDue%')
            ->orWhereIn('name', ['ViewAny:Post', 'View:Post', 'Create:Post', 'Update:Post', 'Delete:Post'])
            ->get());

        // Pengurus: kegiatan + lihat anggota & divisi + artikel sendiri
        $pengurus->syncPermissions(Permission::where('name', 'like', '%Activity%')
            ->orWhereIn('name', [
                'ViewAny:User', 'View:User',
                'ViewAny:Division', 'View:Division',
                'ViewAny:Post', 'View:Post', 'Create:Post', 'Update:Post', 'Delete:Post',
            ])
            ->get());

        // Anggota: lihat kegiatan & voting + artikel sendiri
        $anggota->syncPermissions(Permission::whereIn('name', [
            'ViewAny:Activity', 'View:Activity',
            'ViewAny:Vote', 'View:Vote',
            'ViewAny:Post', 'View:Post', 'Create:Post', 'Update:Post', 'Delete:Post',
            'ViewAny:MemberPoint', 'View:MemberPoint',
        ])->get());

        // Auditor: read-only semua + akses audit
        $auditor->syncPermissions(Permission::where('name', 'like', 'ViewAny:%')
            ->orWhere('name', 'like', 'View:%')
            ->orWhere('name', 'like', '%Audit%')
            ->get());
    }
}
