import { apiClient } from "./client";
import { ApiResponse } from "@/types/api";

/**
 * 권한 그룹 인터페이스
 */
export interface RoleGroup {
  objid: number;
  authName: string;
  authCode: string;
  companyCode: string;
  status: string;
  writer: string;
  regdate: string;
  memberCount?: number;
  menuCount?: number;
  memberNames?: string;
}

/**
 * 권한 그룹 멤버 인터페이스
 */
export interface RoleMember {
  objid: number;
  masterObjid: number;
  userId: string;
  userName: string;
  deptName?: string;
  positionName?: string;
  writer: string;
  regdate: string;
}

/**
 * 메뉴 권한 인터페이스
 */
export interface MenuPermission {
  objid: number;
  menuObjid: number;
  authObjid: number;
  menuName?: string;
  createYn: string;
  readYn: string;
  updateYn: string;
  deleteYn: string;
  writer: string;
  regdate: string;
}

/**
 * 권한 그룹 API
 */
export const roleAPI = {
  /**
   * 권한 그룹 목록 조회
   */
  async getList(params?: { companyCode?: string; search?: string }): Promise<ApiResponse<RoleGroup[]>> {
    try {
      const response = await apiClient.get("/roles", { params });
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "권한 그룹 목록 조회 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 상세 조회
   */
  async getById(id: number): Promise<ApiResponse<RoleGroup>> {
    try {
      const response = await apiClient.get(`/roles/${id}`);
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "권한 그룹 상세 조회 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 생성
   */
  async create(data: { authName: string; authCode: string; companyCode: string }): Promise<ApiResponse<RoleGroup>> {
    try {
      const response = await apiClient.post("/roles", data);
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "권한 그룹 생성 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 수정
   */
  async update(
    id: number,
    data: {
      authName?: string;
      authCode?: string;
      status?: string;
    },
  ): Promise<ApiResponse<RoleGroup>> {
    try {
      const response = await apiClient.put(`/roles/${id}`, data);
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "권한 그룹 수정 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 삭제
   */
  async delete(id: number): Promise<ApiResponse<null>> {
    try {
      const response = await apiClient.delete(`/roles/${id}`);
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "권한 그룹 삭제 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 멤버 목록 조회
   */
  async getMembers(roleId: number): Promise<ApiResponse<RoleMember[]>> {
    try {
      const response = await apiClient.get(`/roles/${roleId}/members`);
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "멤버 목록 조회 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 멤버 추가 (여러 명)
   */
  async addMembers(roleId: number, userIds: string[]): Promise<ApiResponse<null>> {
    try {
      const response = await apiClient.post(`/roles/${roleId}/members`, { userIds });
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "멤버 추가 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 멤버 제거 (여러 명)
   */
  async removeMembers(roleId: number, userIds: string[]): Promise<ApiResponse<null>> {
    try {
      const response = await apiClient.delete(`/roles/${roleId}/members`, { data: { userIds } });
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "멤버 제거 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 권한 그룹 멤버 일괄 업데이트 (기존 멤버 전체 교체)
   */
  async updateMembers(roleId: number, userIds: string[]): Promise<ApiResponse<null>> {
    try {
      const response = await apiClient.put(`/roles/${roleId}/members`, { userIds });
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "멤버 업데이트 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 전체 메뉴 목록 조회 (권한 설정용)
   */
  async getAllMenus(companyCode?: string): Promise<ApiResponse<any[]>> {
    try {
      console.log("🔍 [roleAPI.getAllMenus] API 호출", { companyCode });

      const url = companyCode ? `/roles/menus/all?companyCode=${companyCode}` : "/roles/menus/all";

      const response = await apiClient.get(url);

      console.log("✅ [roleAPI.getAllMenus] API 응답", {
        success: response.data.success,
        count: response.data.data?.length,
      });

      return response.data;
    } catch (error: any) {
      console.error("❌ [roleAPI.getAllMenus] API 에러", error);
      return {
        success: false,
        message: error.response?.data?.message || "전체 메뉴 목록 조회 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 메뉴 권한 목록 조회
   */
  async getMenuPermissions(roleId: number): Promise<ApiResponse<MenuPermission[]>> {
    try {
      const response = await apiClient.get(`/roles/${roleId}/menu-permissions`);
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "메뉴 권한 조회 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 메뉴 권한 설정
   */
  async setMenuPermissions(
    roleId: number,
    permissions: Array<{
      menuObjid: number;
      createYn: string;
      readYn: string;
      updateYn: string;
      deleteYn: string;
    }>,
  ): Promise<ApiResponse<null>> {
    try {
      const response = await apiClient.put(`/roles/${roleId}/menu-permissions`, { permissions });
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "메뉴 권한 설정 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },

  /**
   * 사용자가 속한 권한 그룹 목록 조회
   */
  async getUserRoleGroups(userId?: string): Promise<ApiResponse<RoleGroup[]>> {
    try {
      const url = userId ? `/roles/user/${userId}/groups` : "/roles/user/my-groups";
      const response = await apiClient.get(url);
      return response.data;
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || "사용자 권한 그룹 조회 실패",
        error: error.response?.data?.error || error.message,
      };
    }
  },
};
