import api from './client'

/**
 * UIWS 이식 모듈 API 클라이언트. MES axios 인스턴스(client.ts, JWT 인터셉터) 재사용.
 * uiws 백엔드 컨트롤러 prefix 는 /api/worklogs · /api/schedules · /api/messages · /api/stats
 * (MES 기존 /api/mes/* 라우트와 미충돌). 2FA verify 는 /api/mes/auth/verify.
 * 응답 봉투: { success, message, data }. 호출부는 res.data.data 로 페이로드 접근.
 */

// ── 2FA (MES AuthController: /api/mes/auth/verify)
export const verify2fa = (verifyToken: string, code: string) =>
  api.post('/api/mes/auth/verify', { verifyToken, code })

// ── 로그인 보조 3종 (MES AuthHelperController: /api/mes/auth/{signup,find-id,reset-password})
//    무인증 접근(permitAll). 응답 래퍼 {success,message,data} 그대로 반환 — 호출부에서 data 추출.
export const signup = (body: { username: string; password: string; displayName?: string; email: string }) =>
  api.post('/api/mes/auth/signup', body)
export const findId = (body: { displayName: string; email: string }) =>
  api.post('/api/mes/auth/find-id', body)
export const resetPassword = (body: { username: string; email: string }) =>
  api.post('/api/mes/auth/reset-password', body)

// ── 쪽지(message)
export const sendMessage = (body: object) => api.post('/api/messages', body)
export const listSent = (params: Record<string, unknown>) => api.get('/api/messages/sent', { params })
export const sentDetail = (id: number) => api.get(`/api/messages/sent/${id}`)
export const deleteSent = (ids: number[]) => api.delete('/api/messages/sent', { data: { ids } })
export const listReceived = (params: Record<string, unknown>) => api.get('/api/messages/received', { params })
export const receivedDetail = (id: number) => api.get(`/api/messages/received/${id}`)
export const deleteReceived = (ids: number[]) => api.delete('/api/messages/received', { data: { ids } })
export const unreadCount = () => api.get('/api/messages/unread-count')

// ── 일정(schedule)
export const scheduleCalendar = (params: Record<string, unknown>) => api.get('/api/schedules', { params })
export const scheduleAll = (params: Record<string, unknown>) => api.get('/api/schedules/all', { params })
export const scheduleSearch = (keyword: string) => api.get('/api/schedules/search', { params: { keyword } })
export const createSchedule = (body: object) => api.post('/api/schedules', body)
export const scheduleDetail = (id: number) => api.get(`/api/schedules/${id}`)
export const updateSchedule = (id: number, body: object) => api.put(`/api/schedules/${id}`, body)
export const deleteSchedule = (id: number) => api.delete(`/api/schedules/${id}`)

// ── 일지(diary)
export const diaryList = (params: Record<string, unknown>) => api.get('/api/diaries', { params })
export const createDiary = (body: object) => api.post('/api/diaries', body)
export const diaryDetail = (id: number) => api.get(`/api/diaries/${id}`)
export const updateDiary = (id: number, body: object) => api.put(`/api/diaries/${id}`, body)
export const deleteDiary = (id: number) => api.delete(`/api/diaries/${id}`)

// ── 첨부(attachment)
export const uploadAttachment = (refType: string, refId: number, file: File) => {
  const fd = new FormData()
  fd.append('refType', refType)
  fd.append('refId', String(refId))
  fd.append('file', file)
  return api.post('/api/attachments', fd, { headers: { 'Content-Type': 'multipart/form-data' } })
}
export const deleteAttachment = (id: number) => api.delete(`/api/attachments/${id}`)
export const attachmentDownloadUrl = (id: number) => `/api/attachments/${id}/download`

// ── 업무일지(worklog)
export const worklogList = (params: Record<string, unknown>) => api.get('/api/worklogs', { params })
export const worklogCalendar = (params: Record<string, unknown>) => api.get('/api/worklogs/calendar', { params })
export const worklogSearch = (params: Record<string, unknown>) => api.get('/api/worklogs/search', { params })
export const worklogProgress = (params: Record<string, unknown>) => api.get('/api/worklogs/dashboard/progress', { params })
export const createWorklog = (body: object) => api.post('/api/worklogs', body)
export const worklogDetail = (id: number) => api.get(`/api/worklogs/${id}`)
export const updateWorklog = (id: number, body: object) => api.put(`/api/worklogs/${id}`, body)
export const deleteWorklog = (id: number) => api.delete(`/api/worklogs/${id}`)
export const addWorklogComment = (id: number, cmtContent: string) =>
  api.post(`/api/worklogs/${id}/comments`, { cmtContent })
export const confirmWorklogComment = (cmtId: number) => api.post(`/api/worklogs/comments/${cmtId}/confirm`)

// ── 통계(stats)
export const personalWorkStats = (params: Record<string, unknown>) => api.get('/api/stats/personal-work', { params })
export const companyWorkStats = (params: Record<string, unknown>) => api.get('/api/stats/company-work', { params })

// ── 시스템관리(권한) — com.zioinfo.mes.uiws.system, base /api/system/*
//    MES 백엔드 계약은 CMS 차용분과 동일(실측): 목록 PageResponse(data.content), codes 는 그룹+값 일괄,
//    roles/menus/companies 삭제는 { ids } 본문, depts 삭제는 path, role-menus 엔드포인트 존재.
//    SUPERADMIN 전용(403). 응답 봉투 {success,message,data} → 호출부는 res.data.data 접근.

// 역할(roles) — 목록(paged)/상세/등록/수정/다중삭제
export const roleList = (keyword?: string, page = 0, size = 100) =>
  api.get('/api/system/roles', { params: { ...(keyword ? { keyword } : {}), page, size } })
export const roleDetail = (id: string) => api.get(`/api/system/roles/${encodeURIComponent(id)}`)
export const createRole = (body: object) => api.post('/api/system/roles', body)
export const updateRole = (id: string, body: object) => api.put(`/api/system/roles/${encodeURIComponent(id)}`, body)
export const deleteRoles = (ids: string[]) => api.delete('/api/system/roles', { data: { ids } })

// 역할-메뉴 권한(role-menus) — 역할목록(paged) / 권한별 메뉴매핑 조회·저장
export const roleMenuRoles = (page = 0, size = 100) => api.get('/api/system/role-menus', { params: { page, size } })
export const roleMenuMapping = (roleId: string) => api.get(`/api/system/roles/${encodeURIComponent(roleId)}/menus`)
export const saveRoleMenuMapping = (roleId: string, menus: object[]) =>
  api.put(`/api/system/roles/${encodeURIComponent(roleId)}/menus`, { menus })

// 공통코드(codes) — 그룹목록(paged)/그룹상세(values 포함)/그룹+값 일괄 CRUD
export const codeGroupList = (keyword?: string, page = 0, size = 100) =>
  api.get('/api/system/codes', { params: { ...(keyword ? { keyword } : {}), page, size } })
export const codeGroupDetail = (grpCd: string) => api.get(`/api/system/codes/${encodeURIComponent(grpCd)}`)
export const createCodeGroup = (body: object) => api.post('/api/system/codes', body)
export const updateCodeGroup = (grpCd: string, body: object) =>
  api.put(`/api/system/codes/${encodeURIComponent(grpCd)}`, body)
export const deleteCodeGroup = (grpCd: string) => api.delete(`/api/system/codes/${encodeURIComponent(grpCd)}`)

// 메뉴(menus) — 목록(paged)/검색/등록/수정/다중삭제
export const menuList = (page = 0, size = 200) => api.get('/api/system/menus', { params: { page, size } })
export const menuSearch = (keyword?: string) => api.get('/api/system/menus/search', { params: keyword ? { keyword } : {} })
export const createMenu = (body: object) => api.post('/api/system/menus', body)
export const updateMenu = (id: string, body: object) => api.put(`/api/system/menus/${encodeURIComponent(id)}`, body)
export const deleteMenus = (ids: string[]) => api.delete('/api/system/menus', { data: { ids } })

// 부서(depts) — 목록(paged)/CRUD/단건삭제(path)
export const deptList = (keyword?: string, page = 0, size = 200) =>
  api.get('/api/system/depts', { params: { ...(keyword ? { keyword } : {}), page, size } })
export const createDept = (body: object) => api.post('/api/system/depts', body)
export const updateDept = (id: string, body: object) => api.put(`/api/system/depts/${encodeURIComponent(id)}`, body)
export const deleteDept = (id: string) => api.delete(`/api/system/depts/${encodeURIComponent(id)}`)

// 거래처(companies) — 목록(paged)/CRUD/다중삭제
export const companyList = (keyword?: string, page = 0, size = 200) =>
  api.get('/api/system/companies', { params: { ...(keyword ? { keyword } : {}), page, size } })
export const createCompany = (body: object) => api.post('/api/system/companies', body)
export const updateCompany = (id: string, body: object) => api.put(`/api/system/companies/${encodeURIComponent(id)}`, body)
export const deleteCompanies = (ids: string[]) => api.delete('/api/system/companies', { data: { ids } })
