"use server";

import {
  serverFetchJson,
  serverFetchWithNoContent,
} from "../../../utils/fetchUtil";
import { BASE_API_URL } from "../../../../config/api";
import { revalidateTag } from "next/cache";
import { PrinterResult } from ".";

export interface PrinterInputs {
  name?: string;
  code?: string;
  type?: string;
  brand?: string;
  description?: string;
  ip?: string;
  port?: number;
  dpi?: number;
}

export const fetchPrinterDetails = async (id: number) => {
  return serverFetchJson<PrinterResult>(`${BASE_API_URL}/printers/${id}`, {
    next: { tags: ["printers"] },
  });
};

export const editPrinter = async (id: number, data: PrinterInputs) => {
  const result = await serverFetchWithNoContent(`${BASE_API_URL}/printers/${id}`, {
    method: "PUT",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("printers");
  return result;
};

export const createPrinter = async (data: PrinterInputs) => {
  const result = await serverFetchWithNoContent(`${BASE_API_URL}/printers`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("printers");
  return result;
};

export const deletePrinter = async (id: number) => {
  const result = await serverFetchWithNoContent(`${BASE_API_URL}/printers/${id}`, {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("printers");
  return result;
};

export const fetchPrinterDescriptions = async () => {
  return serverFetchJson<string[]>(`${BASE_API_URL}/printers/descriptions`, {
    next: { tags: ["printers"] },
  });
};
