"use server";

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


export interface CreateGroupInputs {
    id?: number;
    name: string;
    description: string;
    addUserIds?: number[];
    removeUserIds?: number[];
    addAuthIds?: number[];
    removeAuthIds?: number[];
  }

export interface auth {
    id: number;
    module?: any | null;
    authority: string;
    name: string;
    description: string | null;
    v: number;
  }

export interface record {
    records: auth[];
  }

export const fetchAuth = cache(async (target: string, id?: number ) => {
  return serverFetchJson<record>(`${BASE_API_URL}/group/auth/${target}/${id ?? 0}`, {
      next: { tags: ["auth"] },
  });
});
  
export const saveGroup = async (data: CreateGroupInputs) => {
  const newGroup = serverFetchJson(`${BASE_API_URL}/group/save`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("group")
  return newGroup
  };
  
export const deleteGroup = async (id: number) => {
  const newGroup = serverFetchWithNoContent(`${BASE_API_URL}/group/${id}`, {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("group")
  return newGroup
};