<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Services\PermissionAnalyzeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PermissionAnalyzeController extends Controller
{
    public function __construct(
        private PermissionAnalyzeService $service
    ) {}

    /**
     * 메뉴 트리 조회 (HTMX용)
     */
    public function menuTree(Request $request): JsonResponse|string
    {
        $tenantId = session('selected_tenant_id');
        $search = $request->input('search');

        $menuTree = $this->service->getMenuTree($tenantId, $search);

        if ($request->header('HX-Request')) {
            $html = view('permission-analyze.partials.menu-tree', [
                'menuTree' => $menuTree,
            ])->render();

            return response()->json(['html' => $html]);
        }

        return response()->json([
            'success' => true,
            'data' => $menuTree,
        ]);
    }

    /**
     * 특정 메뉴의 권한 분석
     */
    public function analyzeMenu(Request $request): JsonResponse|string
    {
        $menuId = $request->input('menu_id');
        $permissionType = $request->input('permission_type', 'view');
        $tenantId = session('selected_tenant_id');

        if (! $menuId) {
            return response()->json([
                'success' => false,
                'message' => '메뉴를 선택해주세요.',
            ], 400);
        }

        $analysis = $this->service->analyzeMenuPermission($menuId, $permissionType, $tenantId);

        if ($request->header('HX-Request')) {
            $html = view('permission-analyze.partials.analysis-result', [
                'analysis' => $analysis,
                'permissionType' => $permissionType,
            ])->render();

            return response()->json(['html' => $html]);
        }

        return response()->json([
            'success' => true,
            'data' => $analysis,
        ]);
    }

    /**
     * 사용자 역추적
     */
    public function traceUsers(Request $request): JsonResponse|string
    {
        $menuId = $request->input('menu_id');
        $permissionType = $request->input('permission_type', 'view');
        $tenantId = session('selected_tenant_id');

        if (! $menuId) {
            return response()->json([
                'success' => false,
                'message' => '메뉴를 선택해주세요.',
            ], 400);
        }

        $trace = $this->service->traceUsersWithPermission($menuId, $permissionType, $tenantId);

        if ($request->header('HX-Request')) {
            $html = view('permission-analyze.partials.trace-result', [
                'trace' => $trace,
                'permissionType' => $permissionType,
            ])->render();

            return response()->json(['html' => $html]);
        }

        return response()->json([
            'success' => true,
            'data' => $trace,
        ]);
    }

    /**
     * CSV 내보내기
     */
    public function exportCsv(Request $request): Response
    {
        $menuId = $request->input('menu_id');
        $permissionType = $request->input('permission_type', 'view');
        $tenantId = session('selected_tenant_id');

        if (! $menuId) {
            return response('메뉴를 선택해주세요.', 400);
        }

        $csv = $this->service->exportToCsv($menuId, $permissionType, $tenantId);

        $filename = "permission_analysis_{$menuId}_{$permissionType}_".date('Ymd_His').'.csv';

        return response($csv)
            ->header('Content-Type', 'text/csv; charset=UTF-8')
            ->header('Content-Disposition', "attachment; filename=\"{$filename}\"")
            ->header('Content-Transfer-Encoding', 'binary');
    }

    /**
     * 권한 재계산 (캐시 무효화)
     */
    public function recalculate(Request $request): JsonResponse
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        return response()->json([
            'success' => true,
            'message' => '권한이 재계산되었습니다.',
        ]);
    }
}
