import api, { PageResponse, unwrap } from './request';

export interface ApprovalLineRow extends Record<string, unknown> {
  lineId: number;
  lineName: string;
  description: string;
  stepCount: number;
  status: string;
  createdAt: string;
  steps?: ApprovalStep[];
}

export interface ApprovalStep extends Record<string, unknown> {
  stepId: number;
  lineId: number;
  stepOrder: number;
  approverId: number;
  approverName: string;
  approverTitle?: string;
  role: string;
}

export interface ApprovalRequestRow extends Record<string, unknown> {
  requestId: number;
  lineId: number;
  lineName: string;
  requesterId: number;
  requesterName: string;
  title: string;
  content: string;
  currentStep: number;
  totalSteps: number;
  status: string;           // PENDING / IN_PROGRESS / APPROVED / REJECTED
  currentApproverName?: string;
  requestedAt: string;
  completedAt?: string;
  steps?: ApprovalRequestStep[];
}

export interface ApprovalRequestStep extends Record<string, unknown> {
  stepId: number;
  stepOrder: number;
  approverId: number;
  approverName: string;
  status: string;   // PENDING / APPROVED / REJECTED
  comment?: string;
  processedAt?: string;
}

export interface ApprovalLineSaveReq {
  lineName: string;
  description: string;
  steps: { stepOrder: number; approverId: number; role: string }[];
}

export interface ApprovalRequestSaveReq {
  lineId: number;
  title: string;
  content: string;
}

export interface ApprovalSearchParam {
  status?: string;
  requesterId?: number;
  pageNum?: number;
  pageSize?: number;
}

export const approvalApi = {
  // Lines
  lines: (p?: ApprovalSearchParam) =>
    unwrap<PageResponse<ApprovalLineRow>>(
      api.get('/api/approvals/lines', { params: p }),
    ),
  lineCreate: (body: ApprovalLineSaveReq) =>
    unwrap<ApprovalLineRow>(api.post('/api/approvals/lines', body)),
  lineUpdate: (id: number, body: Partial<ApprovalLineSaveReq>) =>
    unwrap<ApprovalLineRow>(api.put(`/api/approvals/lines/${id}`, body)),
  lineDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/approvals/lines/${id}`)),

  // Requests
  requests: (p?: ApprovalSearchParam) =>
    unwrap<PageResponse<ApprovalRequestRow>>(
      api.get('/api/approvals/requests', { params: p }),
    ),
  myRequests: (p?: ApprovalSearchParam) =>
    unwrap<PageResponse<ApprovalRequestRow>>(
      api.get('/api/approvals/requests/mine', { params: p }),
    ),
  pendingRequests: (p?: ApprovalSearchParam) =>
    unwrap<PageResponse<ApprovalRequestRow>>(
      api.get('/api/approvals/requests/pending', { params: p }),
    ),
  requestCreate: (body: ApprovalRequestSaveReq) =>
    unwrap<ApprovalRequestRow>(api.post('/api/approvals/requests', body)),
  requestDetail: (id: number) =>
    unwrap<ApprovalRequestRow>(api.get(`/api/approvals/requests/${id}`)),
  advance: (id: number, body: { approved: boolean; comment?: string }) =>
    unwrap<void>(api.post(`/api/approvals/requests/${id}/advance`, body)),
};
