<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tenants\Department;
use App\Services\DepartmentPermissionService;
use Illuminate\Http\Request;

class DepartmentPermissionController extends Controller
{
    protected DepartmentPermissionService $departmentPermissionService;

    public function __construct(DepartmentPermissionService $departmentPermissionService)
    {
        $this->departmentPermissionService = $departmentPermissionService;
    }

    /**
     * 부서의 tenant_id 조회 (세션이 'all'이거나 미선택일 때 사용)
     */
    protected function getEffectiveTenantId(Request $request, ?int $departmentId = null): ?int
    {
        $sessionTenantId = session('selected_tenant_id');

        // 세션에 특정 테넌트가 선택되어 있으면 그것을 사용
        if ($sessionTenantId && $sessionTenantId !== 'all') {
            return (int) $sessionTenantId;
        }

        // 'all'이거나 미선택일 때는 부서의 tenant_id를 사용
        if ($departmentId) {
            $department = Department::find($departmentId);

            return $department?->tenant_id;
        }

        return null;
    }

    /**
     * 권한 매트릭스 조회 (부서 변경 시 호출)
     */
    public function getMatrix(Request $request)
    {
        $departmentId = $request->input('department_id');
        $guardName = $request->input('guard_name', 'api');

        if (! $departmentId) {
            return view('department-permissions.partials.empty-state');
        }

        // 부서의 tenant_id로 메뉴 필터링
        $tenantId = $this->getEffectiveTenantId($request, $departmentId);

        // 메뉴 트리 조회 (부서의 테넌트 기준)
        $menus = $this->departmentPermissionService->getMenuTree($tenantId);

        // 권한 매트릭스 조회
        $permissions = $this->departmentPermissionService->getDepartmentPermissionMatrix($departmentId, $tenantId, $guardName);

        return view('department-permissions.partials.permission-matrix', [
            'menus' => $menus,
            'permissions' => $permissions,
            'departmentId' => $departmentId,
        ]);
    }

    /**
     * 권한 토글
     */
    public function toggle(Request $request)
    {
        $departmentId = $request->input('department_id');
        $menuId = $request->input('menu_id');
        $permissionType = $request->input('permission_type');
        $guardName = $request->input('guard_name', 'api');
        $tenantId = $this->getEffectiveTenantId($request, $departmentId);

        $newValue = $this->departmentPermissionService->togglePermission(
            $departmentId,
            $menuId,
            $permissionType,
            $tenantId,
            $guardName
        );

        // 전체 매트릭스 다시 로드
        $menus = $this->departmentPermissionService->getMenuTree($tenantId);
        $permissions = $this->departmentPermissionService->getDepartmentPermissionMatrix($departmentId, $tenantId, $guardName);

        return view('department-permissions.partials.permission-matrix', [
            'menus' => $menus,
            'permissions' => $permissions,
            'departmentId' => $departmentId,
        ]);
    }

    /**
     * 전체 허용
     */
    public function allowAll(Request $request)
    {
        $departmentId = $request->input('department_id');
        $guardName = $request->input('guard_name', 'api');
        $tenantId = $this->getEffectiveTenantId($request, $departmentId);

        $this->departmentPermissionService->allowAllPermissions($departmentId, $tenantId, $guardName);

        // 전체 매트릭스 다시 로드
        $menus = $this->departmentPermissionService->getMenuTree($tenantId);
        $permissions = $this->departmentPermissionService->getDepartmentPermissionMatrix($departmentId, $tenantId, $guardName);

        return view('department-permissions.partials.permission-matrix', [
            'menus' => $menus,
            'permissions' => $permissions,
            'departmentId' => $departmentId,
        ]);
    }

    /**
     * 전체 거부
     */
    public function denyAll(Request $request)
    {
        $departmentId = $request->input('department_id');
        $guardName = $request->input('guard_name', 'api');
        $tenantId = $this->getEffectiveTenantId($request, $departmentId);

        $this->departmentPermissionService->denyAllPermissions($departmentId, $tenantId, $guardName);

        // 전체 매트릭스 다시 로드
        $menus = $this->departmentPermissionService->getMenuTree($tenantId);
        $permissions = $this->departmentPermissionService->getDepartmentPermissionMatrix($departmentId, $tenantId, $guardName);

        return view('department-permissions.partials.permission-matrix', [
            'menus' => $menus,
            'permissions' => $permissions,
            'departmentId' => $departmentId,
        ]);
    }

    /**
     * 기본 권한으로 초기화 (view만 허용)
     */
    public function reset(Request $request)
    {
        $departmentId = $request->input('department_id');
        $guardName = $request->input('guard_name', 'api');
        $tenantId = $this->getEffectiveTenantId($request, $departmentId);

        $this->departmentPermissionService->resetToDefaultPermissions($departmentId, $tenantId, $guardName);

        // 전체 매트릭스 다시 로드
        $menus = $this->departmentPermissionService->getMenuTree($tenantId);
        $permissions = $this->departmentPermissionService->getDepartmentPermissionMatrix($departmentId, $tenantId, $guardName);

        return view('department-permissions.partials.permission-matrix', [
            'menus' => $menus,
            'permissions' => $permissions,
            'departmentId' => $departmentId,
        ]);
    }
}
