import {
  httpGetRequest,
  httpPostRequest,
  httpPutRequest,
  httpDeleteRequest,
  APIUrlGenerator,
} from "@/utils/baseHttpService";
import { API_ROUTES } from "@/constant/routes";
import {
  Product,
  ProductVariant,
  CreateProductRequest,
  UpdateProductRequest,
  CreateVariantRequest,
  UpdateVariantRequest,
  ProductsResponse,
  ProductResponse,
  CreateProductResponse,
  UpdateProductResponse,
  DeleteProductResponse,
  ProductVariantsResponse,
  CreateVariantResponse,
  UpdateVariantResponse,
  DeleteVariantResponse,
  ProductFilters,
} from "./_models";

// Products API
export const getProducts = async (filters?: ProductFilters) => {
  try {
    const queryParams: Record<string, string | number | null> = {};

    if (filters?.search) queryParams.search = filters.search;
    if (filters?.category_id) queryParams.category_id = filters.category_id;
    if (filters?.status) queryParams.status = filters.status;
    if (filters?.min_price) queryParams.min_price = filters.min_price;
    if (filters?.max_price) queryParams.max_price = filters.max_price;
    if (filters?.page) queryParams.page = filters.page;
    if (filters?.limit) queryParams.limit = filters.limit;

    const response = await httpGetRequest<ProductsResponse>(
      APIUrlGenerator(API_ROUTES.GET_PRODUCTS, queryParams, undefined, false)
    );

    console.log("Products API Response:", response);

    if (
      response.data &&
      response.data.products &&
      Array.isArray(response.data.products)
    ) {
      // Normalize products for UI consumption
      const normalizedProducts = response.data.products.map((p: any) => {
        // Derive price from first variant if direct price is absent
        const firstVariant = (p.product_variants || p.variants || [])[0] || {};
        const price = p.price ?? firstVariant.price_amount ?? 0;

        // Determine primary category
        const primaryCategory = (p.product_categories || p.categories || [])[0];

        // Map enabled boolean to status string expected by UI components
        const status = p.status ?? (p.enabled ? "active" : "inactive");

        return {
          ...p,
          price,
          category: primaryCategory,
          status,
        };
      });

      return {
        products: normalizedProducts,
        total: response.data.total,
        page: response.data.page,
        per_page: response.data.per_page,
      };
    }

    console.warn("Products is null or not an array:", response.data);
    return { products: [], total: 0, page: 1, per_page: 10 };
  } catch (error) {
    console.error("Error fetching products:", error);
    return { products: [], total: 0, page: 1, per_page: 10 };
  }
};

export const getProduct = async (id: string) => {
  const response = await httpGetRequest<ProductResponse>(
    APIUrlGenerator(API_ROUTES.GET_PRODUCT(id), undefined, undefined, false)
  );
  return response.data.product;
};

export const createProduct = async (data: CreateProductRequest) => {
  const response = await httpPostRequest<CreateProductResponse>(
    APIUrlGenerator(API_ROUTES.CREATE_PRODUCT, undefined, undefined, false),
    data
  );
  return response.data.product;
};

export const updateProduct = async (data: UpdateProductRequest) => {
  const response = await httpPutRequest<UpdateProductResponse>(
    APIUrlGenerator(
      API_ROUTES.UPDATE_PRODUCT(data.id.toString()),
      undefined,
      undefined
    ),
    data
  );
  return response.data.product;
};

export const deleteProduct = async (id: string) => {
  const response = await httpDeleteRequest<DeleteProductResponse>(
    APIUrlGenerator(API_ROUTES.DELETE_PRODUCT(id), undefined, undefined, false)
  );
  return response.data;
};

// Product Variants API
export const getProductVariants = async (productId: string) => {
  try {
    const response = await httpGetRequest<ProductVariantsResponse>(
      APIUrlGenerator(
        API_ROUTES.GET_PRODUCT_VARIANTS(productId),
        undefined,
        undefined,
        false
      )
    );

    console.log("Product Variants API Response:", response);

    if (
      response.data &&
      response.data.variants &&
      Array.isArray(response.data.variants)
    ) {
      return response.data.variants;
    }

    console.warn("Product variants is null or not an array:", response.data);
    return [];
  } catch (error) {
    console.error("Error fetching product variants:", error);
    return [];
  }
};

export const createProductVariant = async (data: CreateVariantRequest) => {
  const response = await httpPostRequest<CreateVariantResponse>(
    APIUrlGenerator(
      API_ROUTES.CREATE_PRODUCT_VARIANT(data.product_id?.toString() || ""),
      undefined,
      undefined,
      false
    ),
    data
  );
  return response.data.variant;
};

export const updateProductVariant = async (data: UpdateVariantRequest) => {
  const response = await httpPutRequest<UpdateVariantResponse>(
    APIUrlGenerator(
      API_ROUTES.UPDATE_PRODUCT_VARIANT(data.id.toString()),
      undefined,
      undefined,
      false
    ),
    data
  );
  return response.data.variant;
};

export const deleteProductVariant = async (variantId: string) => {
  const response = await httpDeleteRequest<DeleteVariantResponse>(
    APIUrlGenerator(
      API_ROUTES.DELETE_PRODUCT_VARIANT(variantId),
      undefined,
      undefined,
      false
    )
  );
  return response.data;
};
