"use server"

import { serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { cache } from "react";
import { PositionResult } from ".";
import { revalidateTag } from "next/cache";

export interface comboProp {
  id: any;
  label: string;
}

export interface combo {
  records: comboProp[];
}

export interface CreatePositionInputs {
    positionCode: string;
    positionName: string;
    code: string;
    name: string;
    description: string;
}

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

export const savePosition = async (data: CreatePositionInputs) => {
    const newPosition = serverFetchJson(`${BASE_API_URL}/positions/new`, {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    });

    revalidateTag("positions")
    return newPosition
  };

export const editPosition = async (data: EditPositionInputs) => {
  const editPostion = serverFetchJson(`${BASE_API_URL}/positions/new`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });

  revalidateTag("positions")
  return editPostion
};

export const deletePosition = async (id: number) => {
  const position = await serverFetchWithNoContent(
      `${BASE_API_URL}/positions/${id}`,
      {
          method: "DELETE",
          headers: { "Content-Type": "application/json" },
      },
  );

  revalidateTag("positions")
  return position
};  

export const fetchPositionCombo = cache(async () => {
  return serverFetchJson<combo>(`${BASE_API_URL}/positions/combo`, {
    next: { tags: ["positions"] },
  });
});

export const fetchPositionDetails = cache(async (id: number) => {
  return serverFetchJson<PositionResult[]>(`${BASE_API_URL}/positions/${id}`, {
    next: { tags: ["positionsDetails"] },
  });
});