import axios from 'axios'

/**
 * UIWS 이식 모듈 API 클라이언트(HRM).
 * 기존 HRM client(baseURL=/api/hrm)와 달리 UIWS 업무 모듈은 top-level /api 경로를 쓰므로
 * baseURL='' 의 전용 인스턴스를 둔다. JWT 토큰은 HRM 동일 키(hrm_token) 재사용.
 * 업무 prefix: /api/worklogs · /api/schedules · /api/messages · /api/stats.
 * 2FA verify: HRM 인증 prefix /api/hrm/auth/verify.
 * 응답 봉투: { success, message, data }. 호출부는 res.data.data 로 페이로드 접근.
 */
const api = axios.create({ baseURL: '' })

api.interceptors.request.use(cfg => {
  const token = localStorage.getItem('hrm_token')
  if (token) cfg.headers.Authorization = `Bearer ${token}`
  return cfg
})

api.interceptors.response.use(
  r => r,
  err => {
    if (err.response?.status === 401) {
      localStorage.removeItem('hrm_token')
      if (location.pathname !== '/login') location.href = '/login'
    }
    return Promise.reject(err)
  }
)

// ── 2FA
// verify2fa: 이메일 인증코드 경로(하위호환). verifyMethod=EMAIL 일 때 사용.
export const verify2fa = (verifyToken: string, code: string) =>
  api.post('/api/hrm/auth/verify', { verifyToken, code })
// verifyOtp: Authenticator(TOTP) 경로. verifyMethod=OTP | OTP_SETUP 일 때 사용.
export const verifyOtp = (verifyToken: string, code: string) =>
  api.post('/api/hrm/auth/verify-otp', { verifyToken, code })

// ── 로그인 보조 3종 (UIWS auth 이식, /api/auth permitAll)
export const signup = (body: { username: string; password: string; displayName: string; email: string }) =>
  api.post('/api/auth/signup', body)
export const findId = (body: { displayName: string; email: string }) =>
  api.post('/api/auth/find-id', body)
export const resetPasswordHelper = (body: { username: string; email: string }) =>
  api.post('/api/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.hrm.uiws.system 컨트롤러 계약 정합(실측).
 * 봉투: { success, message, data }. 목록은 data.content(PageResponse). 쓰기는 SUPERADMIN, 조회는 SUPERADMIN/MANAGER.
 * 삭제 방식이 자원별로 다름: roles/companies/menus = 다중삭제(DELETE body {ids}),
 * depts/codes = 단건삭제(DELETE /{id}|{grpCd}). 코드는 그룹 단위(values 내장).
 */

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

// 공통코드(codes) — 그룹목록 / 그룹상세(values 내장) / 그룹 CRUD(단건삭제)
export const codeGroupList = (keyword?: string, page = 0, size = 100) =>
  api.get('/api/system/codes', { params: { keyword, page, size } })
export const codeGroupDetail = (grpCd: string) => api.get(`/api/system/codes/${grpCd}`)
export const createCodeGroup = (body: object) => api.post('/api/system/codes', body)
export const updateCodeGroup = (grpCd: string, body: object) => api.put(`/api/system/codes/${grpCd}`, body)
export const deleteCodeGroup = (grpCd: string) => api.delete(`/api/system/codes/${grpCd}`)

// 메뉴(menus) — 트리목록(PageResponse) / 등록 / 수정 / 단건삭제(MenuController는 다중삭제 본문 {ids})
export const menuList = (page = 0, size = 200) => api.get('/api/system/menus', { params: { page, size } })
export const createMenu = (body: object) => api.post('/api/system/menus', body)
export const updateMenu = (id: string, body: object) => api.put(`/api/system/menus/${id}`, body)
export const deleteMenu = (id: string) => api.delete('/api/system/menus', { data: { ids: [id] } })

// 부서(depts) — 목록(PageResponse) / CRUD(단건삭제)
export const deptList = (keyword?: string, page = 0, size = 200) =>
  api.get('/api/system/depts', { params: { 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/${id}`, body)
export const deleteDept = (id: string) => api.delete(`/api/system/depts/${id}`)

// 거래처(companies) — 목록(PageResponse) / 등록 / 수정 / 단건삭제(CompanyController는 다중삭제 본문 {ids})
export const companyList = (keyword?: string, page = 0, size = 200) =>
  api.get('/api/system/companies', { params: { 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/${id}`, body)
export const deleteCompany = (id: string) => api.delete('/api/system/companies', { data: { ids: [id] } })

// 권한-메뉴 매핑(role-menus) — 권한목록 / 권한별 메뉴매핑 조회·저장 (HRM에 존재, PMS엔 없었음)
export const roleMenuRoleList = (page = 0, size = 200) =>
  api.get('/api/system/role-menus', { params: { page, size } })
export const roleMenus = (roleId: string) => api.get(`/api/system/roles/${roleId}/menus`)
export const saveRoleMenus = (roleId: string, menus: object[]) =>
  api.put(`/api/system/roles/${roleId}/menus`, { menus })
