// src/features/orders/orderApi.js
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const orderApi = createApi({
  reducerPath: "orderApi",
  baseQuery: fetchBaseQuery({
    baseUrl: import.meta.env.VITE_API_URL,
    prepareHeaders: (headers, { getState }) => {
      const token = getState().auth?.token;
      if (token) headers.set("Authorization", `Bearer ${token}`);
      return headers;
    },
  }),
  endpoints: (builder) => ({
    getOrders: builder.query({
      query: ({ page = 1, limit = 10 }) =>
        `/admin/orders?page=${page}&limit=${limit}`,
      providesTags: ["Orders"],
    }),

    // ✅ ADD THIS
    getOrderById: builder.query({
      query: (id) => `/admin/orders/${id}`,
      providesTags: ["Orders"],
    }),

    // =====================================================
    // UPDATE ORDER STATUS (Delivery Admin)
    // Used in: Order Details Page (Update to SHIPPED / DELIVERED etc.)
    // =====================================================
    updateOrderStatus: builder.mutation({
      query: ({ id, status, trackingNumber }) => ({
        url: `/delivery/admin/${id}/status`,
        method: "PUT",
        body: {
          status,
          trackingNumber,
        },
      }),
      invalidatesTags: ["Orders"], // better
    }),

    getOrderHistory: builder.query({
      query: (id) => `/admin/${id}/history`,
    }),

    // REQUESTED APPROVED REJECTEDCOMPLETED

    // =====================================================
    // RETURN REQUESTS (Admin - Pending / Approved / Rejected)
    // Used in: Admin → Returns → Requests List
    // Status: REQUESTED | APPROVED | REJECTED
    // =====================================================
    getReturnRequests: builder.query({
      query: ({ page = 1, limit = 10 }) =>
        `/orders/admin/returns?page=${page}&limit=${limit}`,
      providesTags: ["Returns"],
    }),

    // =====================================================
    // RETURN HISTORY (Admin - Completed / All Return Records)
    // Used in: Admin → Returns → History Page
    // =====================================================

    getReturnedOrders: builder.query({
      query: ({ page = 1, limit = 10 }) =>
        `/orders/admin/returns/list?page=${page}&limit=${limit}`,
      providesTags: ["Returns"],
    }),

    // =====================================================
    // RETURN DETAILS (Single Return Order)
    // Used in: Admin → Returns → View Details Page
    // URL: /returns/:id
    // =====================================================

    getReturnRequestById: builder.query({
      query: (id) => `/orders/admin/returns/${id}`,
      providesTags: (result, error, id) => [{ type: "Returns", id }],
    }),

    // =====================================================
    // UPDATE RETURN STATUS
    // Used in: ReturnDetails page (Approve / Reject buttons)
    // action = "APPROVE" | "REJECT"
    // =====================================================
    updateReturnStatus: builder.mutation({
      query: ({ id, action }) => ({
        url: `/${id}/return/status`,
        method: "PUT",
        body: { action }, // action = "APPROVE" | "REJECT"
      }),
      invalidatesTags: ["Returns"],
    }),
  }),
});

export const {
  useGetOrdersQuery,
  useGetOrderByIdQuery,
  useGetReturnRequestsQuery,
  useGetReturnedOrdersQuery,
  useGetReturnRequestByIdQuery,
  useUpdateReturnStatusMutation,
  useUpdateOrderStatusMutation,
  useGetOrderHistoryQuery,
} = orderApi;
