import axios from "@/config/axios";
import type { GetOrdersResponse, GetOrderByIdResponse } from "../types/Types";

export interface GetOrdersParams {
  page?: number;
  limit?: number;
  search?: string;
  statuses?: string[];
  paymentStatus?: string;
}

export interface ChangeOrderStatusParams {
  description?: string;
}

export interface RefundPaymentParams {
  description: string;
}

export const getOrders = async (
  params?: GetOrdersParams
): Promise<GetOrdersResponse> => {
  const queryParams = new URLSearchParams();
  
  if (params?.page) {
    queryParams.append('page', params.page.toString());
  }
  
  if (params?.limit) {
    queryParams.append('limit', params.limit.toString());
  }
  
  if (params?.search) {
    queryParams.append('search', params.search);
  }
  
  if (params?.statuses && Array.isArray(params.statuses) && params.statuses.length > 0) {
    params.statuses.forEach((status) => {
      queryParams.append('statuses', status);
    });
  }
  
  if (params?.paymentStatus) {
    queryParams.append('paymentStatus', params.paymentStatus);
  }
  
  const queryString = queryParams.toString();
  const url = queryString ? `/admin/orders?${queryString}` : '/admin/orders';
  
  const { data } = await axios.get<GetOrdersResponse>(url);
  return data;
};

export const getOrderById = async (
  orderId: string
): Promise<GetOrderByIdResponse> => {
  const { data } = await axios.get<GetOrderByIdResponse>(
    `/admin/orders/${orderId}`
  );
  return data;
};

export const confirmOrder = async (orderId: string): Promise<void> => {
  await axios.patch(`/admin/orders/${orderId}/confirm`);
};

export const verifyCashPayment = async (paymentId: string): Promise<void> => {
  await axios.post(`/admin/payments/verify-cash-method/${paymentId}`);
};

export const changeOrderStatus = async (
  orderId: string,
  status: string,
  params?: ChangeOrderStatusParams
): Promise<void> => {
  await axios.patch(`/admin/orders/${orderId}/${status}`, params);
};

export const refundPayment = async (
  orderId: string,
  params: RefundPaymentParams
): Promise<void> => {
  await axios.post(`/admin/orders/${orderId}/refund`, params);
};
