import { api } from "@/lib/api-client";
import type { PaginationParams, ApiSuccessResponse } from "@/types";

export interface ApprovalStage {
  id?: number;
  /** 1-based UI position; serialized alongside sequence for compatibility. */
  order: number;
  sequence?: number;
  approver_id: number;
  approver_name: string;
  max_days?: number;
  auto_escalate?: boolean;
  notification_email?: string;
  status?: "pending" | "approved" | "rejected" | "skipped";
  comment?: string;
  acted_at?: string | null;
}

export interface ApprovalWorkflow {
  id: number;
  name: string;
  type?: string;
  entity_id: number | null;
  entity_name: string | null;
  steps: ApprovalStage[];
  status: "draft" | "active" | "archived";
  allow_bypass?: boolean;
  stage_count?: number;
  request_count?: number;
  created_at: string;
}

export interface ApprovalWorkflowListResponse {
  items?: ApprovalWorkflow[];
  results?: ApprovalWorkflow[];
  total: number;
}

export const approvalsService = {
  async list(params?: PaginationParams & { status?: string; entity_id?: number }): Promise<ApprovalWorkflowListResponse> {
    return api.get<ApprovalWorkflowListResponse>(
      "/approval-workflows",
      params as Record<string, string | number | boolean | undefined>,
    );
  },

  async get(id: number): Promise<ApprovalWorkflow> {
    return api.get<ApprovalWorkflow>(`/approval-workflows/${id}`);
  },

  async create(data: Partial<ApprovalWorkflow> & { steps?: Partial<ApprovalStage>[]; bypass_enabled?: boolean }): Promise<ApprovalWorkflow> {
    return api.post<ApprovalWorkflow>("/approval-workflows", data);
  },

  async update(id: number, data: Partial<ApprovalWorkflow> & { steps?: Partial<ApprovalStage>[]; bypass_enabled?: boolean }): Promise<ApprovalWorkflow> {
    return api.patch<ApprovalWorkflow>(`/approval-workflows/${id}`, data);
  },

  async delete(id: number): Promise<ApiSuccessResponse> {
    return api.delete<ApiSuccessResponse>(`/approval-workflows/${id}`);
  },

  async listUsers(search?: string): Promise<{ items: { id: number; name: string; login: string; email?: string }[]; total: number }> {
    return api.get("/approval-users", search ? { search } : undefined);
  },
};
