<?php

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

/**
 * Add the `branches.view_all` permission and grant it to the roles that manage
 * a whole academy.
 *
 * PermissionSeeder also lists this permission, but db:seed only runs when
 * RUN_SEED_ON_FIRST_DEPLOY is true (docker/entrypoint.sh), so a client deployed
 * outside the one-click template would never receive it. Migrations always run,
 * so this guarantees delivery.
 *
 * Idempotent: every insert checks for an existing row first, so repeated
 * container starts are harmless.
 */
return new class extends Migration
{
    private const PERMISSION = 'branches.view_all';

    private const ROLES = ['super_admin', 'academy_owner', 'academy_admin'];

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

        $permissionId = DB::table('permissions')
            ->where('name', self::PERMISSION)
            ->value('id');

        if (! $permissionId) {
            $permissionId = DB::table('permissions')->insertGetId([
                'name' => self::PERMISSION,
                'module' => 'branches',
                'action' => 'view_all',
                'description' => 'View aggregated data across every branch',
                'description_ar' => 'عرض بيانات كل الفروع مجتمعة',
                'created_at' => now(),
            ]);
        }

        if (! Schema::hasTable('roles')) {
            return;
        }

        // Roles are per-academy, so this covers every tenant in the database.
        $roleIds = DB::table('roles')
            ->whereIn('slug', self::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,
                    'scope' => 'all',
                    'created_at' => now(),
                ]);
            }
        }
    }

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

        $permissionId = DB::table('permissions')
            ->where('name', self::PERMISSION)
            ->value('id');

        if (! $permissionId) {
            return;
        }

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

        DB::table('permissions')->where('id', $permissionId)->delete();
    }
};
