<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration {
    public function up(): void
    {
        $now = now();
        foreach (['projects.view' => 'Projeleri görüntüleme', 'projects.manage' => 'Projeleri yönetme'] as $name => $label) {
            DB::table('permissions')->insertOrIgnore(['name' => $name, 'label' => $label, 'created_at' => $now, 'updated_at' => $now]);
        }
        $roles = DB::table('roles')->whereIn('name', ['super_admin', 'admin', 'support'])->pluck('id', 'name');
        $permissions = DB::table('permissions')->whereIn('name', ['projects.view', 'projects.manage'])->pluck('id', 'name');
        foreach (['super_admin', 'admin'] as $role) {
            if (! isset($roles[$role])) continue;
            foreach ($permissions as $permissionId) {
                DB::table('permission_role')->insertOrIgnore(['role_id' => $roles[$role], 'permission_id' => $permissionId, 'created_at' => $now, 'updated_at' => $now]);
            }
        }
        if (isset($roles['support'], $permissions['projects.view'])) {
            DB::table('permission_role')->insertOrIgnore(['role_id' => $roles['support'], 'permission_id' => $permissions['projects.view'], 'created_at' => $now, 'updated_at' => $now]);
        }
    }
    public function down(): void
    {
        $ids = DB::table('permissions')->whereIn('name', ['projects.view', 'projects.manage'])->pluck('id');
        DB::table('permission_role')->whereIn('permission_id', $ids)->delete();
        DB::table('permissions')->whereIn('id', $ids)->delete();
    }
};