// src/api/deal/dealApi.ts
import instance from "../axiosInstance"
import type { DealCard } from "../../models/deal/DealCard"
import type { DealDetail } from "../../models/deal/DealDetail"
import { mapDealCardResponseToDeal } from "../../adapters/responses/dealCardAdapter"
import { mapDealDetailResponseToDealDetail } from "../../adapters/responses/dealDetailAdapter"
import { endpoints } from "@shared/contracts"

const { deals } = endpoints

export type DealPreset = "new" | "hot" | "trending"

const PRESET_ENDPOINTS: Record<DealPreset, string> = {
  new: "/deals/new",
  hot: "/deals/hot",
  trending: "/deals/trending",
}

const DEFAULT_LIMIT = 10

export async function fetchPresetDeals(
  preset: DealPreset,
  page = 1,
  limit = DEFAULT_LIMIT
): Promise<DealCard[]> {
  const requestData = deals.dealsListRequestSchema.parse({
    q: "",
    page,
    limit,
  })
  const { data } = await instance.get(PRESET_ENDPOINTS[preset], {
    params: requestData,
  })
  const parsed = deals.dealsListResponseSchema.parse(data)
  return parsed.results.map(mapDealCardResponseToDeal)
}

export async function getDeals(page = 1): Promise<DealCard[]> {
  return fetchPresetDeals("new", page, DEFAULT_LIMIT)
}

export async function getDealDetail(id: number): Promise<DealDetail> {
  const { data } = await instance.get(`/deals/${id}`)

  try {
    const parsed = deals.dealDetailResponseSchema.parse(data)
    return mapDealDetailResponseToDealDetail(parsed)
  } catch (e) {
    console.log("DEAL DETAIL RAW:", data)
    console.error("DEAL DETAIL ZOD ERROR:", e)
    throw e
  }
}


export async function fetchCategoryDeals(
  categorySlug: string,  // Category Slug for the specific category
  page = 1,
  limit = DEFAULT_LIMIT
): Promise<DealCard[]> {
  const requestData = deals.dealsListRequestSchema.parse({
    q: "",
    page,
    limit,
    categorySlug,  // Passing categorySlug as a filter
  })
  const { data } = await instance.get(`/category/${categorySlug}/deals`, {
    params: requestData,
  })
console.log(data);
  return data.map(mapDealCardResponseToDeal)
}

// api/category.ts
