import { adminHttp, adminRequest } from "@/lib/admin-http";
import { withAdminAuthHeader } from "@/lib/admin-auth";
import { withAdminLocaleHeaders } from "@/lib/admin-locale";


import type {
  AdminSettlementBatchDetailsData,
  AdminSettlementBatchListData,
  AdminSettlementBatchShowData,
  AdminSettlementRunResponse,
  AdminSettlementWorkflowResponse,
} from "@/types/api/admin-settlement";

const A = `/admin`;

export type AdminSettlementBatchListQuery = {
  page?: number;
  per_page?: number;
  draw_no?: string;
  status?: string;
  agent_node_id?: number;
};

export async function getAdminSettlementBatches(
  q: AdminSettlementBatchListQuery = {},
): Promise<AdminSettlementBatchListData> {
  return adminRequest.get<AdminSettlementBatchListData>(`${A}/settlement-batches`, { params: q });
}

export async function getAdminSettlementBatch(batchId: number): Promise<AdminSettlementBatchShowData> {
  return adminRequest.get<AdminSettlementBatchShowData>(`${A}/settlement-batches/${batchId}`);
}

export type AdminSettlementBatchDetailsQuery = {
  page?: number;
  per_page?: number;
  agent_node_id?: number;
};

export async function getAdminSettlementBatchDetails(
  batchId: number,
  q: AdminSettlementBatchDetailsQuery = {},
): Promise<AdminSettlementBatchDetailsData> {
  return adminRequest.get<AdminSettlementBatchDetailsData>(
    `${A}/settlement-batches/${batchId}/details`,
    { params: q },
  );
}

export async function postAdminRunDrawSettlement(drawId: number): Promise<AdminSettlementRunResponse> {
  return adminRequest.post<AdminSettlementRunResponse>(`${A}/draws/${drawId}/settlement/run`);
}

export async function postAdminApproveSettlementBatch(
  batchId: number,
  remark?: string,
): Promise<AdminSettlementWorkflowResponse> {
  return adminRequest.post<AdminSettlementWorkflowResponse>(
    `${A}/settlement-batches/${batchId}/approve`,
    { remark },
  );
}

export async function postAdminRejectSettlementBatch(
  batchId: number,
  remark?: string,
): Promise<AdminSettlementWorkflowResponse> {
  return adminRequest.post<AdminSettlementWorkflowResponse>(
    `${A}/settlement-batches/${batchId}/reject`,
    { remark },
  );
}

export async function postAdminPayoutSettlementBatch(batchId: number): Promise<AdminSettlementWorkflowResponse> {
  return adminRequest.post<AdminSettlementWorkflowResponse>(`${A}/settlement-batches/${batchId}/payout`);
}

export async function downloadAdminSettlementBatchExport(batchId: number): Promise<Blob> {
  const res = await adminHttp.request<Blob>(
    withAdminAuthHeader(withAdminLocaleHeaders({
      url: `${A}/settlement-batches/${batchId}/export`,
      method: "GET",
      responseType: "blob",
    })),
  );
  return res.data;
}
