<?php

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

return new class extends Migration
{
    /** @var list<string> */
    private const STALE_PERMISSION_CODES = [
        'dashboard.view',
        'service.reports.view',
        'service.reports.export',
    ];

    public function up(): void
    {
        $menuActionIds = DB::table('admin_menu_actions')
            ->whereIn('permission_code', self::STALE_PERMISSION_CODES)
            ->pluck('id');

        if ($menuActionIds->isNotEmpty()) {
            DB::table('admin_menu_actions')
                ->whereIn('id', $menuActionIds->all())
                ->delete();
        }

        $staleReportMenuId = DB::table('admin_menus')
            ->where('code', 'service.reports')
            ->value('id');

        if ($staleReportMenuId !== null) {
            $hasActions = DB::table('admin_menu_actions')
                ->where('menu_id', (int) $staleReportMenuId)
                ->exists();

            if (! $hasActions) {
                DB::table('admin_menus')
                    ->where('id', (int) $staleReportMenuId)
                    ->delete();
            }
        }
    }

    public function down(): void
    {
        // 数据清理迁移，不回滚以免再现僵尸 permission_code。
    }
};
