import apiClient from "@/infrastructure/apiClient";
import apiPath from "@/infrastructure/apiPath";

export default {
  /**
   * API 1: Tìm kiếm khách hàng có đơn hàng cần tạo hóa đơn
   * @param {Object} searchModel - SmartTableParam object
   * @returns {Promise<Object>} - Search result with customers
   */
  async searchCustomersForTransferPayment(searchModel) {
    const params = JSON.parse(JSON.stringify(searchModel));
    try {
      const response = await apiClient.post(
        apiPath.transferPaymentBill.searchCustomersForTransferPayment,
        params
      );
      return response.data;
    } catch (error) {
      console.error("Error searching customers for transfer payment:", error);
      return {
        items: [],
        totalCount: 0,
        page: 1,
        pageSize: 10,
        totalPages: 0,
      };
    }
  },

  /**
   * API 2: Lấy danh sách đơn hàng có thể tạo hóa đơn
   * @param {Object} params - { customerId }
   * @returns {Promise<Object>} - Orders data
   */
  async getTransferableOrdersByCustomer(params) {
    try {
      const response = await apiClient.get(
        apiPath.transferPaymentBill.getTransferableOrdersByCustomer,
        { params }
      );
      return response.data;
    } catch (error) {
      console.error("Error getting transferable orders:", error);
      return {
        customerId: params.customerId,
        customerName: "",
        customerPhone: "",
        fromDate: params.fromDate,
        toDate: params.toDate,
        orders: [],
        totalTransferFeeAmount: 0,
        totalOrderCount: 0,
      };
    }
  },

  /**
   * API 3: Tạo phiếu chuyển tiền
   * @param {FormData|Object} createModel - CreateTransferPaymentBillModel (FormData for file upload or Object for JSON)
   * @returns {Promise<Object>} - Create result
   */
  async create(createModel) {
    try {
      let dataToSend = createModel;
      let config = {};

      // Check if it's FormData (for file upload)
      if (createModel instanceof FormData) {
        config.headers = { "Content-Type": "multipart/form-data" };
      } else {
        // For backward compatibility with JSON requests
        dataToSend = JSON.parse(JSON.stringify(createModel));
      }

      const response = await apiClient.post(
        apiPath.transferPaymentBill.create,
        dataToSend,
        config
      );
      return response.data;
    } catch (error) {
      console.error("Error creating transfer payment bill:", error);
      return {
        result: "Failed",
        message:
          error.response?.data?.message ||
          "Có lỗi xảy ra khi tạo phiếu chuyển tiền",
        id: null,
        code: null,
        processedOrderCount: 0,
        totalAmount: 0,
      };
    }
  },

  /**
   * API 4: Tìm kiếm hóa đơn thanh toán
   * @param {Object} searchModel - SmartTableParam object
   * @returns {Promise<Object>} - Search result with bills
   */
  async search(searchModel) {
    const params = JSON.parse(JSON.stringify(searchModel));
    try {
      const response = await apiClient.post(
        apiPath.transferPaymentBill.search,
        params
      );
      return response.data;
    } catch (error) {
      console.error("Error searching transfer payment bills:", error);
      return {
        items: [],
        totalCount: 0,
        page: 1,
        pageSize: 10,
        totalPages: 0,
      };
    }
  },

  /**
   * API 5: Lấy chi tiết hóa đơn
   * @param {number} id - Bill ID
   * @returns {Promise<Object>} - Bill detail
   */
  async getById(id) {
    try {
      const response = await apiClient.get(
        `${apiPath.transferPaymentBill.getById}${id}`
      );
      return response.data;
    } catch (error) {
      console.error("Error getting transfer payment bill detail:", error);
      return null;
    }
  },

  /**
   * API 6: Hủy hóa đơn
   * @param {Object} cancelData - Cancel data
   * @param {number} cancelData.transferPaymentBillId - Bill ID
   * @param {string} cancelData.cancelReason - Cancel reason
   * @param {string} cancelData.note - Additional note
   * @param {boolean} cancelData.createOrderTrack - Create order track
   * @param {boolean} cancelData.sendNotification - Send notification
   * @returns {Promise<Object>} - Cancel result
   */
  async cancel(cancelData) {
    try {
      const response = await apiClient.post(
        apiPath.transferPaymentBill.cancel,
        cancelData
      );
      return response.data;
    } catch (error) {
      console.error("Error cancelling transfer payment bill:", error);
      return {
        result: "Failed",
        message:
          error.response?.data?.message || "Có lỗi xảy ra khi hủy hóa đơn",
        id: cancelData.transferPaymentBillId,
        code: null,
      };
    }
  },

  /**
   * API 7: Duyệt hóa đơn
   * @param {Object} approveModel - ApproveTransferPaymentBillModel
   * @returns {Promise<Object>} - Approve result
   */
  async approve(approveModel) {
    const params = JSON.parse(JSON.stringify(approveModel));
    try {
      const response = await apiClient.post(
        apiPath.transferPaymentBill.approve,
        params
      );
      return response.data;
    } catch (error) {
      console.error("Error approving transfer payment bill:", error);
      return {
        result: "Failed",
        message:
          error.response?.data?.message || "Có lỗi xảy ra khi duyệt hóa đơn",
        id: approveModel.id,
        code: null,
        processedOrderCount: 0,
        totalAmount: 0,
      };
    }
  },

  /**
   * API 8: Kiểm tra quyền
   * @param {Object} params - { billId, action }
   * @returns {Promise<Object>} - Permission check result
   */
  async checkPermission(params) {
    try {
      const response = await apiClient.get(
        apiPath.transferPaymentBill.checkPermission,
        { params }
      );
      return response.data;
    } catch (error) {
      console.error("Error checking permission:", error);
      return {
        hasPermission: false,
      };
    }
  },
};
