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

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

/**
 * 부서 목록 조회 (회사별).
 * options.includeDeleted=true 시 soft-delete 된 부서도 포함.
 * options.baseDate (YYYY-MM-DD) 가 있으면 해당 시점에 active 한 부서만 반환.
 */
export async function getDepartments(
  companyCode: string,
  options?: { includeDeleted?: boolean; baseDate?: string },
) {
  try {
    const url = `/departments/companies/${companyCode}/departments`;
    const params: Record<string, any> = {};
    if (options?.includeDeleted) params.include_deleted = true;
    if (options?.baseDate) params.base_date = options.baseDate;
    const response = await apiClient.get<{ success: boolean; data: Department[] }>(url, {
      params: Object.keys(params).length > 0 ? params : undefined,
    });
    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 };
  }
}

/**
 * 부서 삭제 (V1: soft-delete).
 * 응답 호환: 기존 { success, message } 에 data.soft_deleted=true 필드 추가.
 */
export async function deleteDepartment(deptCode: string) {
  try {
    const response = await apiClient.delete<{
      success: boolean;
      message?: string;
      data?: { soft_deleted?: boolean; dept_code?: string };
    }>(`/departments/${deptCode}`);
    return response.data;
  } catch (error: any) {
    console.error("부서 삭제 실패:", error);
    return { success: false, error: error.message };
  }
}

/**
 * 부서 복구 (V1 신규 — soft-delete 된 부서 되살리기).
 * 부모가 deleted 면 차단 (400) → "상위 부서를 먼저 복구해주세요" 메시지.
 */
export async function restoreDepartment(deptCode: string) {
  try {
    const response = await apiClient.post<{
      success: boolean;
      message?: string;
      data?: { dept_code?: string; restored?: boolean };
    }>(`/departments/${deptCode}/restore`);
    return response.data;
  } catch (error: any) {
    console.error("부서 복구 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || 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 };
  }
}

// ──────────────────────────────────────────────────
// 일괄등록 / 일괄업데이트
// ──────────────────────────────────────────────────

export type BulkAction = "create" | "update_department" | "update_manager";

export interface BulkPreviewRow extends Record<string, any> {
  row_index: number;
  result: "ok" | "error";
  error_detail: string | null;
}

/**
 * 일괄 미리보기 — read-only validation, write 없음.
 * action 에 따라 create/update_department/update_manager 로 검증.
 * 응답 rows 각 element 에 result(ok|error), error_detail 채워짐.
 */
export async function bulkPreviewDepartments(
  companyCode: string,
  action: BulkAction,
  rows: Record<string, any>[],
) {
  try {
    const response = await apiClient.post<{
      success: boolean;
      data?: { rows: BulkPreviewRow[]; ok_count: number; error_count: number };
      message?: string;
    }>(`/departments/companies/${companyCode}/departments/bulk/preview`, { action, rows });
    return response.data;
  } catch (error: any) {
    console.error("일괄 미리보기 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 일괄등록 적용 (트랜잭션, all-or-nothing).
 * rows 는 보통 미리보기에서 ok 인 row 만 보냄.
 */
export async function bulkCreateDepartments(companyCode: string, rows: Record<string, any>[]) {
  try {
    const response = await apiClient.post<{
      success: boolean;
      data?: { inserted: number };
      message?: string;
    }>(`/departments/companies/${companyCode}/departments/bulk/create`, { rows });
    return response.data;
  } catch (error: any) {
    console.error("일괄등록 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 일괄업데이트 적용 (트랜잭션). mode = department | manager.
 * 각 row 에 dept_code 필수.
 */
export async function bulkUpdateDepartments(
  companyCode: string,
  mode: "department" | "manager",
  rows: Record<string, any>[],
) {
  try {
    const response = await apiClient.post<{
      success: boolean;
      data?: { updated: number };
      message?: string;
    }>(`/departments/companies/${companyCode}/departments/bulk/update`, { mode, rows });
    return response.data;
  } catch (error: any) {
    console.error("일괄업데이트 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}
