"use server";

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

export interface UserInputs {
    username: string;
    name: string;
    email?: string;
    addAuthIds?: number[];
    removeAuthIds?: number[];
    password?: string;
}

export interface PasswordInputs {
    password: string;
    newPassword: string;
    newPasswordCheck: string;
}

export const fetchUserDetails = cache(async (id: number) => {
    return serverFetchJson<UserDetail>(`${BASE_API_URL}/user/${id}`, {
      next: { tags: ["user"] },
    });
  });

export const editUser = async (id: number, data: UserInputs) => {
  const newUser = serverFetchWithNoContent(`${BASE_API_URL}/user/${id}`, {
    method: "PUT",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("user")
  return newUser
  };

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

export const changePassword = async (data: any) => {
    return serverFetchWithNoContent(`${BASE_API_URL}/user/change-password`, {
      method: "PATCH",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    });
  };

export const adminChangePassword = async (data: any) => {
    return serverFetchWithNoContent(`${BASE_API_URL}/user/admin-change-password`, {
      method: "PATCH",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    });
  };