<?php

namespace App\Support;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

/**
 * 代理线路开通、占成授信、代理账单等 permission_code 的 menu_action 补救（auth-sync 前须存在）。
 */
final class AdminAgentLineSettlementPermissionMenuActionSync
{
    public static function syncMissing(): int
    {
        $now = Carbon::now();
        $viewActionId = DB::table('admin_action_catalog')->where('code', 'view')->value('id');
        $manageActionId = DB::table('admin_action_catalog')->where('code', 'manage')->value('id');
        if ($viewActionId === null || $manageActionId === null) {
            return 0;
        }

        $created = 0;

        $agentMenuId = (int) DB::table('admin_menus')->where('code', 'system.agents')->value('id');
        if ($agentMenuId > 0) {
            $lineMenuId = self::ensureChildMenu($agentMenuId, 'system.agents.line', '代理线路开通', $now, 'system.agents');
            $profileMenuId = self::ensureChildMenu($agentMenuId, 'system.agents.profile', '代理占成授信', $now, 'system.agents');
            $created += self::ensureMenuAction($lineMenuId, (int) $manageActionId, 'agent.line.provision', '代理线路开通', $now) ? 1 : 0;
            $created += self::ensureMenuAction($profileMenuId, (int) $manageActionId, 'agent.profile.manage', '代理占成授信管理', $now) ? 1 : 0;
        }

        $settlementBatchMenuId = (int) DB::table('admin_menus')->where('code', 'settlement.batch')->value('id');
        if ($settlementBatchMenuId > 0) {
            $agentBillMenuId = self::ensureChildMenu(
                $settlementBatchMenuId,
                'settlement.batch.agent',
                '代理账单',
                $now,
                'settlement.batch',
            );
            $created += self::ensureMenuAction($agentBillMenuId, (int) $viewActionId, 'settlement.agent.view', '代理账单查看', $now) ? 1 : 0;
            $created += self::ensureMenuAction($agentBillMenuId, (int) $manageActionId, 'settlement.agent.manage', '代理账单管理', $now) ? 1 : 0;
        }

        return $created;
    }

    private static function ensureChildMenu(
        int $parentId,
        string $code,
        string $name,
        Carbon $now,
        string $activeMenuCode = 'system.agents',
    ): int {
        $existing = DB::table('admin_menus')->where('code', $code)->value('id');
        if ($existing !== null) {
            return (int) $existing;
        }

        return (int) DB::table('admin_menus')->insertGetId([
            'parent_id' => $parentId,
            'menu_type' => 'button',
            'code' => $code,
            'name' => $name,
            'path' => null,
            'route_name' => null,
            'component' => null,
            'icon' => null,
            'active_menu_code' => $activeMenuCode,
            'sort_order' => 0,
            'is_visible' => false,
            'is_cache' => false,
            'is_external' => false,
            'status' => 1,
            'meta_json' => null,
            'created_at' => $now,
            'updated_at' => $now,
        ]);
    }

    private static function ensureMenuAction(int $menuId, int $actionId, string $permissionCode, string $name, Carbon $now): bool
    {
        if (DB::table('admin_menu_actions')->where('permission_code', $permissionCode)->exists()) {
            return false;
        }

        DB::table('admin_menu_actions')->insert([
            'menu_id' => $menuId,
            'action_id' => $actionId,
            'permission_code' => $permissionCode,
            'name' => $name,
            'status' => 1,
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        return true;
    }
}
