import type { UserPermissions } from "~/types/permissions";
import { MOCK_PERMISSIONS } from "~/types/permissions";

export const usePermissionsStore = defineStore(
  "permissions",
  () => {
    // 권한 데이터 상태
    const permissions = ref<UserPermissions>({
      resources: {
        pageGroups: [],
        pages: [],
        components: [],
      },
    });

    // 서버에서 권한 데이터 가져오기 (현재는 가데이터 사용)
    const fetchPermissions = async (): Promise<boolean> => {
      const { withLoading } = useLoading();

      return await withLoading(async () => {
        // 실제 API 호출 (백엔드 준비되면 주석 해제)
        /*
        const { success, data } = await useApi<UserPermissions>('/auth/permissions', {
          method: 'GET',
          handleError: false
        });

        if (success && data) {
          permissions.value = {
            resources: {
              pageGroups: data.resources?.pageGroups || [],
              pages: data.resources?.pages || [],
              components: data.resources?.components || []
            }
          };
          return true;
        }
        return false;
        */

        // 임시 가데이터 사용
        await new Promise(resolve => setTimeout(resolve, 3000)); // 로딩 시뮬레이션

        permissions.value = {
          resources: {
            pageGroups: [...MOCK_PERMISSIONS.resources.pageGroups],
            pages: [...MOCK_PERMISSIONS.resources.pages],
            components: [...MOCK_PERMISSIONS.resources.components],
          },
        };

        return true;
      }, "권한 정보를 불러오는 중...");
    };

    const getPagePaths = (): string[] => {
      return permissions.value.resources.pages
        .map(page => page.path)
        .filter(Boolean) as string[];
    };

    const getPageGroupCodes = (): string[] => {
      return permissions.value.resources.pageGroups.map(
        pageGroup => pageGroup.code
      );
    };

    const getComponentCodes = (): string[] => {
      return permissions.value.resources.components.map(
        component => component.code
      );
    };

    const hasPagePermission = (page: string): boolean => {
      const pagePaths = getPagePaths();

      // 1. 정확한 경로 매치 먼저 확인
      if (pagePaths.includes(page)) {
        return true;
      }

      // 2. 동적 라우팅 패턴 체크
      for (const allowedPath of pagePaths) {
        // 동적 라우팅 패턴: /[tabId]/path 형태
        const dynamicPattern = new RegExp(`^/\\d+${allowedPath}$`);
        if (dynamicPattern.test(page)) {
          return true;
        }
      }

      return false;
    };

    const hasPageGroupPermission = (pageGroup: string): boolean => {
      return getPageGroupCodes().includes(pageGroup);
    };

    const hasComponentPermission = (component: string): boolean => {
      return getComponentCodes().includes(component);
    };

    // 권한 초기화
    const clearPermissions = () => {
      permissions.value = {
        resources: {
          pageGroups: [],
          pages: [],
          components: [],
        },
      };
    };

    return {
      permissions,

      fetchPermissions,
      clearPermissions,

      hasPagePermission,
      hasPageGroupPermission,
      hasComponentPermission,

      getPagePaths,
      getPageGroupCodes,
      getComponentCodes,
    };
  },
  {
    persist: true,
  }
);
