import { api as client } from "../auth/http";
import { unwrap } from "@/utils/endpoint";
import { URL_CONSTANTS } from "@/constants/URLS";

const P = URL_CONSTANTS.PAYMENTS;

export type PaymentStatus =
  | "action-required"
  | "processing"
  | "success"
  | "failed"
  | "canceled"
  | "refunded";

export type PaymentMethod =
  | "telebirr"
  | "cbe-birr"
  | "ebirr"
  | "waafi"
  | "card"
  | "dmoney"
  | "cac-bank";

export interface PaymentRow {
  id: string;
  bookingId: string;
  amount: number;
  currency: string;
  method: PaymentMethod;
  status: PaymentStatus;
  merchantOrderId: string | null;
  paidAt: string | null;
  createdAt: string;
}

export interface PaymentListFilter {
  search?: string;
  status?: string;
  method?: string;
  page?: number;
  pageSize?: number;
}

export interface PaginatedPayments {
  items: PaymentRow[];
  total: number;
  page: number;
  pageSize: number;
}

export interface PaymentSummary {
  total: number;
  success: number;
  processing: number;
  failed: number;
  refunded: number;
  paidAmount: number;
}

export const paymentsService = {
  list: async (filter?: PaymentListFilter): Promise<PaginatedPayments> => {
    const params: Record<string, string | number | undefined> = {};
    if (filter) {
      if (filter.search) params.search = filter.search;
      if (filter.status) params.status = filter.status;
      if (filter.method) params.method = filter.method;
      if (filter.page != null) params.page = filter.page;
      if (filter.pageSize != null) params.pageSize = filter.pageSize;
    }
    const response = await client.get<PaginatedPayments>(P.ALL, { params });
    const data = unwrap(response.data) as PaginatedPayments;
    return {
      items: data.items ?? [],
      total: data.total ?? 0,
      page: data.page ?? 1,
      pageSize: data.pageSize ?? 10,
    };
  },

  getSummary: async (): Promise<PaymentSummary> => {
    const response = await client.get<PaymentSummary>(P.SUMMARY);
    return unwrap(response.data) as PaymentSummary;
  },
};
