/**
 * 부서 관리 API 클라이언트
 */

import { apiClient } from "./client";
import { Department, DepartmentMember, DepartmentFormData } from "@/types/department";

/**
 * 부서 목록 조회 (회사별)
 */
export async function getDepartments(companyCode: string) {
  try {
    const url = `/departments/companies/${companyCode}/departments`;
    const response = await apiClient.get<{ success: boolean; data: Department[] }>(url);
    return response.data;
  } catch (error: any) {
    console.error("부서 목록 조회 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 부서 상세 조회
 */
export async function getDepartment(deptCode: string) {
  try {
    const response = await apiClient.get<{ success: boolean; data: Department }>(`/departments/${deptCode}`);
    return response.data;
  } catch (error: any) {
    console.error("부서 상세 조회 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 부서 생성
 */
export async function createDepartment(companyCode: string, data: DepartmentFormData) {
  try {
    const response = await apiClient.post<{ success: boolean; data: Department }>(
      `/departments/companies/${companyCode}/departments`,
      data,
    );
    return response.data;
  } catch (error: any) {
    console.error("부서 생성 실패:", error);
    const isDuplicate = error.response?.status === 409;
    return {
      success: false,
      error: error.response?.data?.message || error.message,
      isDuplicate,
    };
  }
}

/**
 * 부서 수정
 */
export async function updateDepartment(deptCode: string, data: DepartmentFormData) {
  try {
    const response = await apiClient.put<{ success: boolean; data: Department }>(`/departments/${deptCode}`, data);
    return response.data;
  } catch (error: any) {
    console.error("부서 수정 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 부서 삭제
 */
export async function deleteDepartment(deptCode: string) {
  try {
    const response = await apiClient.delete<{ success: boolean }>(`/departments/${deptCode}`);
    return response.data;
  } catch (error: any) {
    console.error("부서 삭제 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 부서원 목록 조회
 */
export async function getDepartmentMembers(deptCode: string) {
  try {
    const response = await apiClient.get<{ success: boolean; data: DepartmentMember[] }>(
      `/departments/${deptCode}/members`,
    );
    return response.data;
  } catch (error: any) {
    console.error("부서원 목록 조회 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 사용자 검색 (부서원 추가용)
 */
export async function searchUsers(companyCode: string, search: string) {
  try {
    const response = await apiClient.get<{ success: boolean; data: any[] }>(
      `/departments/companies/${companyCode}/users/search`,
      { params: { search } },
    );
    return response.data;
  } catch (error: any) {
    console.error("사용자 검색 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 부서원 추가
 */
export async function addDepartmentMember(deptCode: string, userId: string) {
  try {
    const response = await apiClient.post<{ success: boolean; message?: string }>(`/departments/${deptCode}/members`, {
      user_id: userId,
    });
    return response.data;
  } catch (error: any) {
    console.error("부서원 추가 실패:", error);
    const isDuplicate = error.response?.status === 409;
    return {
      success: false,
      error: error.response?.data?.message || error.message,
      isDuplicate,
    };
  }
}

/**
 * 부서원 제거
 */
export async function removeDepartmentMember(deptCode: string, userId: string) {
  try {
    const response = await apiClient.delete<{ success: boolean }>(`/departments/${deptCode}/members/${userId}`);
    return response.data;
  } catch (error: any) {
    console.error("부서원 제거 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 주 부서 설정
 */
export async function setPrimaryDepartment(deptCode: string, userId: string) {
  try {
    const response = await apiClient.put<{ success: boolean }>(`/departments/${deptCode}/members/${userId}/primary`);
    return response.data;
  } catch (error: any) {
    console.error("주 부서 설정 실패:", error);
    return { success: false, error: error.message };
  }
}
