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

export const couponApi = createApi({
  reducerPath: "couponApi",
  baseQuery: fetchBaseQuery({
    baseUrl: import.meta.env.VITE_API_URL || "http://localhost:3000/api",
    prepareHeaders: (headers, { getState }) => {
      const token = getState().auth?.token;
      if (token) headers.set("Authorization", `Bearer ${token}`);
      return headers;
    },
  }),
  tagTypes: ["Coupons"],
  endpoints: (builder) => ({
    getCoupons: builder.query({
      query: () => "/admin/coupons",
      transformResponse: (res) => res.data.coupons,
      providesTags: ["Coupons"],
    }),

    // ✅ GET SINGLE COUPON (NEW)
    getCouponById: builder.query({
      query: (id) => `/admin/coupons/${id}`,
      transformResponse: (res) => res.data, // 🔥 IMPORTANT
      providesTags: ["Coupons"],
    }),

    createCoupon: builder.mutation({
      query: (body) => ({
        url: "/admin/coupons",
        method: "POST",
        body,
      }),
      invalidatesTags: ["Coupons"],
    }),

    toggleCouponStatus: builder.mutation({
      query: (id) => ({
        url: `/admin/coupons/${id}/toggle`,
        method: "PATCH",
      }),
      invalidatesTags: ["Coupons"],
    }),
  }),
});

export const {
  useGetCouponsQuery,
  useGetCouponByIdQuery,
  useCreateCouponMutation,
  useToggleCouponStatusMutation,
} = couponApi;
