import { useApi } from './useApi'
import type {
  ApiProject,
  ApiProjectAttachment,
  CreateProjectPayload,
  ProjectListQuery,
  UpdateProjectPayload,
} from '@/types/project'
import type { Paginated } from '@/types/pagination'

// 프로젝트 도메인 API Composable — 인터셉터가 success/data 를 언래핑
export function useProject() {
  const api = useApi()

  // 목록(검색/정렬 + 페이지네이션)
  async function list(
    page = 1,
    size = 20,
    query: ProjectListQuery = {},
  ): Promise<Paginated<ApiProject>> {
    return (await api.get('/projects', {
      params: { ...query, page, size },
    })) as unknown as Paginated<ApiProject>
  }

  async function get(id: string): Promise<ApiProject> {
    return (await api.get(`/projects/${id}`)) as unknown as ApiProject
  }

  async function create(payload: CreateProjectPayload): Promise<ApiProject> {
    return (await api.post('/projects', payload)) as unknown as ApiProject
  }

  async function update(
    id: string,
    payload: UpdateProjectPayload,
  ): Promise<ApiProject> {
    return (await api.patch(`/projects/${id}`, payload)) as unknown as ApiProject
  }

  async function remove(id: string): Promise<void> {
    await api.delete(`/projects/${id}`)
  }

  // 문서 첨부 업로드(관리자) — multipart/form-data
  async function uploadFile(
    projectId: string,
    file: File,
  ): Promise<ApiProjectAttachment> {
    const form = new FormData()
    form.append('file', file)
    return (await api.post(`/projects/${projectId}/files`, form, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })) as unknown as ApiProjectAttachment
  }

  // 문서 첨부 삭제(관리자)
  async function removeFile(projectId: string, fileId: string): Promise<void> {
    await api.delete(`/projects/${projectId}/files/${fileId}`)
  }

  return { list, get, create, update, remove, uploadFile, removeFile }
}
