import { useApi } from './useApi'
import type {
  ApiAttachment,
  ApiComment,
  ApiCommentReply,
  ApiProjectTaskListResult,
  ApiTaskDetail,
  ChecklistReviewItem,
  ChecklistWorkStatus,
  CreateTaskPayload,
  TaskListQuery,
  UpdateTaskPayload,
} from '@/types/task'
import type { TaskStatus } from '@/mock/relay.mock'
import { DEFAULT_PAGE_SIZE } from '@/types/pagination'

// 업무 도메인 API Composable — 인터셉터가 success/data 를 언래핑
// 경로는 모두 projectId 하위: /projects/:projectId/tasks[/:taskId]
export function useTask() {
  const api = useApi()

  // 업무 목록 (세그먼트/검색/담당자 필터 + 페이지네이션) — 응답에 세그먼트 카운트 동봉
  async function list(
    projectId: string,
    query: TaskListQuery = {},
    page = 1,
    size = DEFAULT_PAGE_SIZE,
  ): Promise<ApiProjectTaskListResult> {
    return (await api.get(`/projects/${projectId}/tasks`, {
      params: { ...query, page, size },
    })) as unknown as ApiProjectTaskListResult
  }

  // 업무 단건 상세 (taskId = 프로젝트 내 순번)
  async function get(projectId: string, taskId: number): Promise<ApiTaskDetail> {
    return (await api.get(`/projects/${projectId}/tasks/${taskId}`)) as unknown as ApiTaskDetail
  }

  // 업무 생성 (admin)
  async function create(projectId: string, payload: CreateTaskPayload): Promise<ApiTaskDetail> {
    return (await api.post(`/projects/${projectId}/tasks`, payload)) as unknown as ApiTaskDetail
  }

  // 업무 수정 (admin)
  async function update(
    projectId: string,
    taskId: number,
    payload: UpdateTaskPayload,
  ): Promise<ApiTaskDetail> {
    return (await api.patch(
      `/projects/${projectId}/tasks/${taskId}`,
      payload,
    )) as unknown as ApiTaskDetail
  }

  // 업무 삭제 (admin)
  async function remove(projectId: string, taskId: number): Promise<void> {
    await api.delete(`/projects/${projectId}/tasks/${taskId}`)
  }

  // 상태 변경 (상태 머신)
  async function changeStatus(
    projectId: string,
    taskId: number,
    status: TaskStatus,
  ): Promise<ApiTaskDetail> {
    return (await api.post(`/projects/${projectId}/tasks/${taskId}/status`, {
      status,
    })) as unknown as ApiTaskDetail
  }

  /* ===================== 중간 점검(체크포인트) ===================== */

  // 중간 점검 보고(담당자) — 점검일 당일, 항목별 상태 + 메모를 보고서로 제출
  async function submitCheckpointReport(
    projectId: string,
    taskId: number,
    checkpointId: string,
    items: { id: string; workStatus: ChecklistWorkStatus }[],
    note?: string,
  ): Promise<ApiTaskDetail> {
    return (await api.post(
      `/projects/${projectId}/tasks/${taskId}/checkpoints/${checkpointId}/report`,
      { items, ...(note ? { note } : {}) },
    )) as unknown as ApiTaskDetail
  }

  /* ===================== 댓글 / 답글 (5단계) ===================== */

  async function addComment(
    projectId: string,
    taskId: number,
    text: string,
    fileId?: string,
  ): Promise<ApiComment> {
    return (await api.post(`/projects/${projectId}/tasks/${taskId}/comments`, {
      text,
      ...(fileId ? { fileId } : {}),
    })) as unknown as ApiComment
  }

  async function addReply(
    projectId: string,
    taskId: number,
    commentId: string,
    text: string,
  ): Promise<ApiCommentReply> {
    return (await api.post(
      `/projects/${projectId}/tasks/${taskId}/comments/${commentId}/replies`,
      { text },
    )) as unknown as ApiCommentReply
  }

  /* ===================== 파일 첨부 (5단계) ===================== */

  async function uploadFile(
    projectId: string,
    taskId: number,
    file: File,
  ): Promise<ApiAttachment> {
    const form = new FormData()
    form.append('file', file)
    return (await api.post(`/projects/${projectId}/tasks/${taskId}/files`, form, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })) as unknown as ApiAttachment
  }

  async function removeFile(
    projectId: string,
    taskId: number,
    fileId: string,
  ): Promise<void> {
    await api.delete(`/projects/${projectId}/tasks/${taskId}/files/${fileId}`)
  }

  /* ===================== 승인 워크플로우 (5단계) ===================== */

  async function requestApproval(
    projectId: string,
    taskId: number,
    note?: string,
  ): Promise<ApiTaskDetail> {
    return (await api.post(`/projects/${projectId}/tasks/${taskId}/approval/request`, {
      ...(note ? { note } : {}),
    })) as unknown as ApiTaskDetail
  }

  async function approve(
    projectId: string,
    taskId: number,
  ): Promise<ApiTaskDetail> {
    return (await api.post(
      `/projects/${projectId}/tasks/${taskId}/approval/approve`,
    )) as unknown as ApiTaskDetail
  }

  async function requestChanges(
    projectId: string,
    taskId: number,
    note: string | undefined,
    checklist?: ChecklistReviewItem[],
  ): Promise<ApiTaskDetail> {
    return (await api.post(`/projects/${projectId}/tasks/${taskId}/approval/changes`, {
      note,
      checklist,
    })) as unknown as ApiTaskDetail
  }

  return {
    list,
    get,
    create,
    update,
    remove,
    changeStatus,
    submitCheckpointReport,
    addComment,
    addReply,
    uploadFile,
    removeFile,
    requestApproval,
    approve,
    requestChanges,
  }
}
