import api from './client'

/**
 * UIWS 이식 모듈 API 클라이언트. 기존 ESN axios 인스턴스(baseURL='', esn_token JWT 인터셉터) 재사용.
 * ESN client 는 baseURL 이 비어 있으므로 전체 경로 /api/... 를 사용한다.
 * 응답 봉투: { success, message, data }. 호출부는 res.data.data 로 페이로드 접근.
 */

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

// ── OTP / 계정 보안 (마이페이지, access 토큰 필요) ─────────────────────────
// 보안 불변: setup 응답(secret/qrImage)은 화면 표시용만 — 로그/저장 금지. 새 비번은 응답/로그 미포함.
export const otpSetup = () => api.post('/api/auth/otp/setup')
export const otpConfirm = (code: string) => api.post('/api/auth/otp/confirm', { code })
export const otpDisable = () => api.post('/api/auth/otp/disable')
export const changePassword = (currentPassword: string, newPassword: string) =>
  api.post('/api/auth/change-password', { currentPassword, newPassword })

// ── 관리자 OTP 초기화 (ADMIN 전용) — zioinfo-esn 은 username 기준. 시크릿 미조회. ──────
export const adminOtpReset = (username: string) =>
  api.post(`/api/admin/users/${encodeURIComponent(username)}/otp-reset`)

// ── 쪽지(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 })

// ── 로그인 보조 3종 (회원가입·아이디찾기·비밀번호초기화) — 비인증(/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 resetPassword = (body: { username: string; email: string }) =>
  api.post('/api/auth/reset-password', body)

// ── system(권한관리) — RBAC: 조회 인증, 변경 ADMIN/MANAGER (백엔드 com.zioinfo.esn.uiws.system, /api/system/*)
// 응답 봉투 { success, message, data }. 목록은 data=PageResponse{content,total,page,size}. 호출부 res.data.data.* 접근.

// 2.1 권한(roles) — keyword/page/size, 다중삭제(본문 ids)
export const roleList = (params: Record<string, unknown>) => api.get('/api/system/roles', { params })
export const roleCreate = (body: object) => api.post('/api/system/roles', body)
export const roleGet = (id: string) => api.get(`/api/system/roles/${id}`)
export const roleUpdate = (id: string, body: object) => api.put(`/api/system/roles/${id}`, body)
export const roleDelete = (ids: string[]) => api.delete('/api/system/roles', { data: { ids } })

// 2.5 메뉴생성(role-menus) — 권한별 메뉴 읽기/쓰기 매핑
export const roleMenuRoles = (params: Record<string, unknown>) => api.get('/api/system/role-menus', { params })
export const roleMenusGet = (roleId: string) => api.get(`/api/system/roles/${roleId}/menus`)
export const roleMenusSave = (roleId: string, menus: object[]) => api.put(`/api/system/roles/${roleId}/menus`, { menus })

// 2.7 코드(codes) — 그룹목록/상세/CRUD + 드롭다운값
export const codeList = (params: Record<string, unknown>) => api.get('/api/system/codes', { params })
export const codeGroupGet = (grpCd: string) => api.get(`/api/system/codes/${grpCd}`)
export const codeValues = (grpCd: string) => api.get(`/api/system/codes/group/${grpCd}/values`)
export const codeCreate = (body: object) => api.post('/api/system/codes', body)
export const codeUpdate = (grpCd: string, body: object) => api.put(`/api/system/codes/${grpCd}`, body)
export const codeDelete = (grpCd: string) => api.delete(`/api/system/codes/${grpCd}`)

// 2.9 메뉴(menus) — 목록/검색/CRUD/다중삭제(본문 ids)
export const menuList = (params: Record<string, unknown>) => api.get('/api/system/menus', { params })
export const menuGet = (id: string) => api.get(`/api/system/menus/${id}`)
export const menuCreate = (body: object) => api.post('/api/system/menus', body)
export const menuUpdate = (id: string, body: object) => api.put(`/api/system/menus/${id}`, body)
export const menuDelete = (ids: string[]) => api.delete('/api/system/menus', { data: { ids } })

// 2.8 프로그램(programs) — 메뉴 연결용
export const programList = (params: Record<string, unknown>) => api.get('/api/system/programs', { params })

// 2.3 부서(depts) — 목록/검색/CRUD(개별삭제 path)
export const deptList = (params: Record<string, unknown>) => api.get('/api/system/depts', { params })
export const deptTree = () => api.get('/api/system/depts/tree')
export const deptGet = (id: string) => api.get(`/api/system/depts/${id}`)
export const deptCreate = (body: object) => api.post('/api/system/depts', body)
export const deptUpdate = (id: string, body: object) => api.put(`/api/system/depts/${id}`, body)
export const deptDelete = (id: string) => api.delete(`/api/system/depts/${id}`)

// 2.4 거래처(companies) — 목록/검색/CRUD/다중삭제(본문 ids)
export const companyList = (params: Record<string, unknown>) => api.get('/api/system/companies', { params })
export const companyGet = (id: string) => api.get(`/api/system/companies/${id}`)
export const companyCreate = (body: object) => api.post('/api/system/companies', body)
export const companyUpdate = (id: string, body: object) => api.put(`/api/system/companies/${id}`, body)
export const companyDelete = (ids: string[]) => api.delete('/api/system/companies', { data: { ids } })
