/*
 * §5B 공통 전자결재(F028) API 클라이언트 — 자체 모듈.
 * ★ 공유 api/endpoints.ts·types.ts 를 수정하지 않기 위해 결재 엔드포인트/타입을 여기에 캡슐화한다.
 *   공용 client.ts 의 api(get/post) 만 재사용하여 JWT·에러 봉투 처리를 공유한다.
 * 백엔드: /api/work/approvals (ApprovalController). 상태: DRAFT→SUBMITTED→IN_PROGRESS→APPROVED|REJECTED(+CANCELED).
 */
import { api } from '../../api/client';
import type { PageResponse } from '../../api/types';

export type ApprovalStatus =
  | 'DRAFT'
  | 'SUBMITTED'
  | 'IN_PROGRESS'
  | 'APPROVED'
  | 'REJECTED'
  | 'CANCELED';

export type ApprovalBox = 'DRAFT' | 'DRAFTED' | 'PENDING' | 'DONE';

export interface ApprovalListItem {
  id: string;
  docType: string;
  title: string;
  status: ApprovalStatus;
  drafterId: string;
  drafterName: string | null;
  curStep: number;
  totalSteps: number;
  version: number;
  eventId: string | null;
  refType: string | null;
  refId: string | null;
  submittedAt: string | null;
  createdAt: string | null;
}

export interface ApprovalLine {
  id: string;
  stepNo: number;
  approverId: string;
  approverName: string | null;
  lineStatus: 'WAIT' | 'CURRENT' | 'APPROVED' | 'REJECTED' | 'SKIPPED';
  actedAt: string | null;
  comment: string | null;
}

export interface ApprovalHistoryItem {
  id: string;
  stepNo: number | null;
  actorId: string;
  actorName: string | null;
  action: 'SUBMIT' | 'APPROVE' | 'REJECT' | 'RESUBMIT' | 'CANCEL';
  comment: string | null;
  actedAt: string | null;
}

export interface ApprovalDetail {
  id: string;
  docType: string;
  title: string;
  content: string | null;
  status: ApprovalStatus;
  drafterId: string;
  drafterName: string | null;
  curStep: number;
  totalSteps: number;
  version: number;
  eventId: string | null;
  refType: string | null;
  refId: string | null;
  submittedAt: string | null;
  completedAt: string | null;
  createdAt: string | null;
  lines: ApprovalLine[];
  history: ApprovalHistoryItem[];
  canAct: boolean;
  canCancel: boolean;
  canResubmit: boolean;
}

export interface ApprovalLineSaveRequest {
  stepNo: number;
  approverId: string;
  approverName?: string;
}

export interface ApprovalSaveRequest {
  eventId?: string;
  docType?: string;
  title: string;
  content?: string;
  refType?: string;
  refId?: string;
  lines?: ApprovalLineSaveRequest[];
}

const BASE = '/api/work/approvals';

export const approvalApi = {
  /** GET / — 결재함 목록(box=DRAFT|DRAFTED|PENDING|DONE). */
  list: (params?: { box?: ApprovalBox; keyword?: string; page?: number; size?: number }) => {
    const q = new URLSearchParams();
    if (params?.box) q.set('box', params.box);
    if (params?.keyword) q.set('keyword', params.keyword);
    if (params?.page != null) q.set('page', String(params.page));
    if (params?.size != null) q.set('size', String(params.size));
    const qs = q.toString();
    return api.get<PageResponse<ApprovalListItem>>(`${BASE}${qs ? `?${qs}` : ''}`);
  },

  /** GET /{id} — 상세(결재선·이력·액션 플래그). */
  get: (id: string) => api.get<ApprovalDetail>(`${BASE}/${encodeURIComponent(id)}`),

  /** POST / — 기안(DRAFT). */
  create: (body: ApprovalSaveRequest) => api.post<ApprovalDetail>(BASE, body),

  /** POST /{id}/submit — 상신. */
  submit: (id: string) => api.post<ApprovalDetail>(`${BASE}/${encodeURIComponent(id)}/submit`),

  /** POST /{id}/approve — 승인(현재 단계 결재자). */
  approve: (id: string, comment?: string) =>
    api.post<ApprovalDetail>(`${BASE}/${encodeURIComponent(id)}/approve`, { comment }),

  /** POST /{id}/reject — 반려(사유 필수). */
  reject: (id: string, comment: string) =>
    api.post<ApprovalDetail>(`${BASE}/${encodeURIComponent(id)}/reject`, { comment }),

  /** POST /{id}/resubmit — 재상신(version+1). */
  resubmit: (id: string, body?: ApprovalSaveRequest) =>
    api.post<ApprovalDetail>(`${BASE}/${encodeURIComponent(id)}/resubmit`, body ?? {}),

  /** POST /{id}/cancel — 회수. */
  cancel: (id: string) => api.post<ApprovalDetail>(`${BASE}/${encodeURIComponent(id)}/cancel`),
};
