"use server";

import { serverFetchJson ,serverFetchWithNoContent} from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { revalidatePath, revalidateTag } from "next/cache";
import {
  ItemQcCategoryMappingInfo,
  QcItemInfo,
  DeleteResponse,
  QcCategoryResult,
  ItemsResult,
  QcItemResult,
} from ".";

export interface SaveQcCategoryInputs {
  id?: number;
  code: string;
  name: string;
  description?: string;
}

export interface SaveQcCategoryResponse {
  id?: number;
  code: string;
  name: string;
  description?: string;
  errors: Record<string, string> | null;
}

export interface SaveQcItemInputs {
  id?: number;
  code: string;
  name: string;
  description?: string;
}

export interface SaveQcItemResponse {
  id?: number;
  code: string;
  name: string;
  description?: string;
  errors: Record<string, string> | null;
}

// Item and QcCategory mapping
export const getItemQcCategoryMappings = async (
  qcCategoryId?: number,
  itemId?: number
): Promise<ItemQcCategoryMappingInfo[]> => {
  const params = new URLSearchParams();
  if (qcCategoryId) params.append("qcCategoryId", qcCategoryId.toString());
  if (itemId) params.append("itemId", itemId.toString());
  
  return serverFetchJson<ItemQcCategoryMappingInfo[]>(
    `${BASE_API_URL}/qcItemAll/itemMappings?${params.toString()}`
  );
};

export const saveItemQcCategoryMapping = async (
  itemId: number,
  qcCategoryId: number,
  type: string
): Promise<ItemQcCategoryMappingInfo> => {
  const params = new URLSearchParams();
  params.append("itemId", itemId.toString());
  params.append("qcCategoryId", qcCategoryId.toString());
  params.append("type", type);
  
  const response = await serverFetchJson<ItemQcCategoryMappingInfo>(
    `${BASE_API_URL}/qcItemAll/itemMapping?${params.toString()}`,
    {
      method: "POST",
    }
  );
  
  revalidateTag("qcItemAll");
  return response;
};

export const deleteItemQcCategoryMapping = async (
  mappingId: number
): Promise<void> => {
  await serverFetchJson<void>(
    `${BASE_API_URL}/qcItemAll/itemMapping/${mappingId}`,
    {
      method: "DELETE",
    }
  );
  
  revalidateTag("qcItemAll");
};

// QcCategory and QcItem mapping
export const getQcCategoryQcItemMappings = async (
  qcCategoryId: number
): Promise<QcItemInfo[]> => {
  return serverFetchJson<QcItemInfo[]>(
    `${BASE_API_URL}/qcItemAll/qcItemMappings/${qcCategoryId}`
  );
};

export const saveQcCategoryQcItemMapping = async (
  qcCategoryId: number,
  qcItemId: number,
  order: number,
  description?: string
): Promise<QcItemInfo> => {
  const params = new URLSearchParams();
  params.append("qcCategoryId", qcCategoryId.toString());
  params.append("qcItemId", qcItemId.toString());
  params.append("order", order.toString());
  if (description) params.append("description", description);
  
  const response = await serverFetchJson<QcItemInfo>(
    `${BASE_API_URL}/qcItemAll/qcItemMapping?${params.toString()}`,
    {
      method: "POST",
    }
  );
  
  revalidateTag("qcItemAll");
  return response;
};

export const deleteQcCategoryQcItemMapping = async (
  mappingId: number
): Promise<void> => {
  await serverFetchJson<void>(
    `${BASE_API_URL}/qcItemAll/qcItemMapping/${mappingId}`,
    {
      method: "DELETE",
    }
  );
  
  revalidateTag("qcItemAll");
};

// Counts
export const getItemCountByQcCategory = async (
  qcCategoryId: number
): Promise<number> => {
  return serverFetchJson<number>(
    `${BASE_API_URL}/qcItemAll/itemCount/${qcCategoryId}`
  );
};

export const getQcItemCountByQcCategory = async (
  qcCategoryId: number
): Promise<number> => {
  return serverFetchJson<number>(
    `${BASE_API_URL}/qcItemAll/qcItemCount/${qcCategoryId}`
  );
};

// Validation
export const canDeleteQcCategory = async (id: number): Promise<boolean> => {
  return serverFetchJson<boolean>(
    `${BASE_API_URL}/qcItemAll/canDeleteQcCategory/${id}`
  );
};

export const canDeleteQcItem = async (id: number): Promise<boolean> => {
  return serverFetchJson<boolean>(
    `${BASE_API_URL}/qcItemAll/canDeleteQcItem/${id}`
  );
};

// Save and delete with validation
export const saveQcCategoryWithValidation = async (
  data: SaveQcCategoryInputs
): Promise<SaveQcCategoryResponse> => {
  const response = await serverFetchJson<SaveQcCategoryResponse>(
    `${BASE_API_URL}/qcItemAll/saveQcCategory`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    }
  );
  
  revalidateTag("qcCategories");
  revalidateTag("qcItemAll");
  return response;
};

export const deleteQcCategoryWithValidation = async (
  id: number
): Promise<DeleteResponse> => {
  const response = await serverFetchJson<DeleteResponse>(
    `${BASE_API_URL}/qcItemAll/deleteQcCategory/${id}`,
    {
      method: "DELETE",
    }
  );
  
  revalidateTag("qcCategories");
  revalidateTag("qcItemAll");
  revalidatePath("/(main)/settings/qcItemAll");
  return response;
};

export const saveQcItemWithValidation = async (
  data: SaveQcItemInputs
): Promise<SaveQcItemResponse> => {
  const response = await serverFetchJson<SaveQcItemResponse>(
    `${BASE_API_URL}/qcItemAll/saveQcItem`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    }
  );
  
  revalidateTag("qcItems");
  revalidateTag("qcItemAll");
  return response;
};

export const deleteQcItemWithValidation = async (
  id: number
): Promise<DeleteResponse> => {
  const response = await serverFetchJson<DeleteResponse>(
    `${BASE_API_URL}/qcItemAll/deleteQcItem/${id}`,
    {
      method: "DELETE",
    }
  );
  
  revalidateTag("qcItems");
  revalidateTag("qcItemAll");
  revalidatePath("/(main)/settings/qcItemAll");
  return response;
};

// Server actions for fetching data (to be used in client components)
export const fetchQcCategoriesForAll = async (): Promise<QcCategoryResult[]> => {
  return serverFetchJson<QcCategoryResult[]>(
    `${BASE_API_URL}/qcItemAll/categoriesWithItemCountsAndType`,
    { next: { tags: ["qcItemAll", "qcCategories"] } }
  );
};
type CategoryTypeResponse = { type: string | null };
export const getCategoryType = async (qcCategoryId: number): Promise<string | null> => {
  const res = await serverFetchJson<CategoryTypeResponse>(
    `${BASE_API_URL}/qcItemAll/categoryType/${qcCategoryId}`
  );
  return res.type ?? null;
};

export const updateCategoryType = async (
  qcCategoryId: number,
  type: string
): Promise<void> => {
  await serverFetchWithNoContent(
    `${BASE_API_URL}/qcItemAll/categoryType?qcCategoryId=${qcCategoryId}&type=${encodeURIComponent(type)}`,
    { method: "PUT" }
  );
  revalidateTag("qcItemAll");
};
export const fetchItemsForAll = async (): Promise<ItemsResult[]> => {
  return serverFetchJson<ItemsResult[]>(`${BASE_API_URL}/items`, {
    next: { tags: ["items"] },
  });
};

export const fetchQcItemsForAll = async (): Promise<QcItemResult[]> => {
  return serverFetchJson<QcItemResult[]>(`${BASE_API_URL}/qcItems`, {
    next: { tags: ["qcItems"] },
  });
};

// Get item by code (for Tab 0 - validate item code input)
export const getItemByCode = async (code: string): Promise<ItemsResult | null> => {
  try {
    return await serverFetchJson<ItemsResult>(`${BASE_API_URL}/qcItemAll/itemByCode/${encodeURIComponent(code)}`);
  } catch (error) {
    // Item not found
    return null;
  }
};



