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

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

    // 권한 로딩 상태
    const isLoading = ref(false);

    // 서버에서 권한 데이터 가져오기 (현재는 가데이터 사용)
    const fetchPermissions = async (): Promise<boolean> => {
      try {
        isLoading.value = true;

        // 실제 API 호출 (백엔드 준비되면 주석 해제)
        /*
        const { success, data } = await useApi<{
          pagePermissions: string[];
          menuPermissions: string[];
          componentPermissions: string[];
        }>('/auth/permissions', {
          method: 'GET',
          handleError: false
        });

        if (success && data) {
          permissions.value = {
            pagePermissions: data.pagePermissions || [],
            menuPermissions: data.menuPermissions || [],
            componentPermissions: data.componentPermissions || []
          };
          return true;
        }
        return false;
        */

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

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

        return true;
      } catch (error) {
        console.error("권한 데이터 로드 실패:", error);
        return false;
      } finally {
        isLoading.value = false;
      }
    };

    // 헬퍼 함수들 - 기존 호환성을 위한 함수들
    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 => {
      return getPagePaths().includes(page);
    };

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

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

    // 여러 권한 중 하나라도 있는지 체크
    const hasAnyPagePermission = (pages: string[]): boolean => {
      return pages.some(page => hasPagePermission(page));
    };

    const hasAnyPageGroupPermission = (pageGroups: string[]): boolean => {
      return pageGroups.some(pageGroup => hasPageGroupPermission(pageGroup));
    };

    const hasAnyComponentPermission = (components: string[]): boolean => {
      return components.some(component => hasComponentPermission(component));
    };

    // 계층 구조를 고려한 권한 체크 함수들
    const hasResourcePermission = (resourceCode: string): boolean => {
      return (
        findResourceByCode(permissions.value.resources, resourceCode) !==
        undefined
      );
    };

    const getResourceByCode = (code: string): Resource | undefined => {
      return findResourceByCode(permissions.value.resources, code);
    };

    const getResourceByPath = (path: string): Resource | undefined => {
      return findResourceByPath(permissions.value.resources, path);
    };

    const getChildResources = (parentCode: string): Resource[] => {
      const parent = findResourceByCode(
        permissions.value.resources,
        parentCode
      );
      return parent?.children || [];
    };

    // 계층 구조에서 리소스 찾기 헬퍼 함수들

    const findResourceByCode = (
      resources: {
        pageGroups: Resource[];
        pages: Resource[];
        components: Resource[];
      },
      code: string
    ): Resource | undefined => {
      const allResources = [
        ...resources.pageGroups,
        ...resources.pages,
        ...resources.components,
      ];
      for (const resource of allResources) {
        if (resource.code === code) return resource;
        if (resource.children) {
          const found = findResourceByCode(
            { pageGroups: [], pages: [], components: resource.children },
            code
          );
          if (found) return found;
        }
      }
      return undefined;
    };

    const findResourceByPath = (
      resources: {
        pageGroups: Resource[];
        pages: Resource[];
        components: Resource[];
      },
      path: string
    ): Resource | undefined => {
      const allResources = [
        ...resources.pageGroups,
        ...resources.pages,
        ...resources.components,
      ];
      for (const resource of allResources) {
        if (resource.path === path) return resource;
        if (resource.children) {
          const found = findResourceByPath(
            { pageGroups: [], pages: [], components: resource.children },
            path
          );
          if (found) return found;
        }
      }
      return undefined;
    };

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

    return {
      // 상태
      permissions: readonly(permissions),
      isLoading: readonly(isLoading),

      // 액션
      fetchPermissions,
      clearPermissions,

      // 기존 호환성 함수들
      hasPagePermission,
      hasPageGroupPermission,
      hasComponentPermission,
      hasAnyPagePermission,
      hasAnyPageGroupPermission,
      hasAnyComponentPermission,

      // 헬퍼 함수들
      getPagePaths,
      getPageGroupCodes,
      getComponentCodes,

      // 새로운 계층 구조 권한 체크 함수들
      hasResourcePermission,
      getResourceByCode,
      getResourceByPath,
      getChildResources,
    };
  },
  {
    persist: true,
  }
);
