"use server";

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

export interface UserInputs {
  username: string;
  name: string;
  staffNo?: string;
  locked?: boolean;
  addAuthIds?: number[];
  removeAuthIds?: number[];
  password?: string;
  confirmPassword?: string;
}

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

export interface NameList {
  id: number;
  name: string;
}

export interface NewNameList {
  id: number;
  name: string;
  title: string;
  department: string;
}

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

export const fetchNameList = cache(async () => {
  return serverFetchJson<NameList[]>(`${BASE_API_URL}/user/name-list`, {
    next: { tags: ["user"] },
  });
});

export const fetchNewNameList = cache(async () => {
  return serverFetchJson<NewNameList[]>(`${BASE_API_URL}/user/new-name-list`, {
    next: { tags: ["user"] },
  });
});

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

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

export const deleteUser = async (id: number) => {
  const newUser = await 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" },
    },
  );
};

export const fetchEscalationCombo = async () => {
  return serverFetchJson<EscalationCombo[]>(`${BASE_API_URL}/user/escalation-combo`, {
    next: { tags: ["escalationCombo"]}
  })
};