<?php

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

/**
 * Permissions for the revenue routing screen.
 *
 * Split in two on purpose: an auditor or a reviewer may need to read the rules
 * to explain a figure without being able to move next month's money. Both go to
 * the four roles that answer for the books — deliberately not to a branch
 * manager, since routing is an academy-wide setting and a branch-scoped grant
 * would be a rule that only half applies. PermissionSeeder grants the same four
 * on a fresh install; the two must not drift.
 *
 * Delivered by migration rather than by PermissionSeeder because db:seed only
 * runs when RUN_SEED_ON_FIRST_DEPLOY is true, so a client installed outside the
 * one-click template would never receive it. Idempotent throughout.
 */
return new class extends Migration
{
    private const PERMISSIONS = [
        'revenue_routing.view' => [
            'action' => 'view',
            'description' => 'View how collected revenue is routed to ledger accounts',
            'description_ar' => 'عرض توجيه الإيرادات على الحسابات',
            'roles' => ['super_admin', 'academy_owner', 'academy_admin', 'accountant'],
        ],
        'revenue_routing.manage' => [
            'action' => 'manage',
            'description' => 'Change revenue routing rules and tax treatment',
            'description_ar' => 'تعديل قواعد توجيه الإيرادات والمعالجة الضريبية',
            'roles' => ['super_admin', 'academy_owner', 'academy_admin', 'accountant'],
        ],
    ];

    public function up(): void
    {
        if (! Schema::hasTable('permissions') || ! Schema::hasTable('permission_role') || ! Schema::hasTable('roles')) {
            return;
        }

        foreach (self::PERMISSIONS as $name => $spec) {
            $permissionId = DB::table('permissions')->where('name', $name)->value('id');

            if (! $permissionId) {
                $permissionId = DB::table('permissions')->insertGetId([
                    'name' => $name,
                    'module' => 'revenue_routing',
                    'action' => $spec['action'],
                    'description' => $spec['description'],
                    'description_ar' => $spec['description_ar'],
                    'created_at' => now(),
                ]);
            }

            // Roles are per-academy rows, so this reaches every tenant.
            $roleIds = DB::table('roles')->whereIn('slug', $spec['roles'])->pluck('id');

            foreach ($roleIds as $roleId) {
                $exists = DB::table('permission_role')
                    ->where('role_id', $roleId)
                    ->where('permission_id', $permissionId)
                    ->exists();

                if (! $exists) {
                    DB::table('permission_role')->insert([
                        'role_id' => $roleId,
                        'permission_id' => $permissionId,
                        // Routing is an academy-wide setting; a branch-scoped
                        // grant would be a rule that only half applies.
                        'scope' => 'all',
                        'created_at' => now(),
                    ]);
                }
            }
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('permissions')) {
            return;
        }

        $ids = DB::table('permissions')->whereIn('name', array_keys(self::PERMISSIONS))->pluck('id');

        if ($ids->isEmpty()) {
            return;
        }

        if (Schema::hasTable('permission_role')) {
            DB::table('permission_role')->whereIn('permission_id', $ids)->delete();
        }

        DB::table('permissions')->whereIn('id', $ids)->delete();
    }
};
