import axiosInstance from "@/shared/services/axiosInstance";

export interface PasswordSettings {
  id?: string;
  minimumPasswordLength: number;
  maximumPasswordLength: number;
  passwordExpiry: number;
  sessionTimeout: number;
  isDefaultPasswordEnabled: boolean;
  defaultPassword?: string;
}

/**
 * Get system password settings
 */
export const getPasswordSettings = async (): Promise<PasswordSettings | null> => {
  const { data } = await axiosInstance.get("/system-configurations");
  console.log("Password settings API response:", data);
  
  // API returns an array with {count, items}
  if (data && data.items && Array.isArray(data.items)) {
    console.log("Found items array, returning first item:", data.items[0]);
    // Return the first (latest) item if it exists
    return data.items[0] || null;
  }
  
  // Fallback for direct object response
  console.log("No items array, returning data as is:", data);
  return data || null;
};

/**
 * Update system password settings
 */
export const updatePasswordSettings = async (
  payload: PasswordSettings
): Promise<PasswordSettings> => {
  const { data } = await axiosInstance.put(
    `/system-configurations/${payload.id}`,
    payload
  );
  return data;
};

/**
 * Create system password settings
 */
export const createPasswordSettings = async (
  payload: PasswordSettings
): Promise<PasswordSettings> => {
  const { data } = await axiosInstance.post(
    "/system-configurations",
    payload
  );
  return data;
};

/**
 * Delete system password settings
 */
export const deletePasswordSettings = async (
  id: string
): Promise<void> => {
  console.log("Calling DELETE /system-configurations/" + id);
  try {
    const response = await axiosInstance.delete(`/system-configurations/${id}`);
    console.log("Delete response:", response);
  } catch (error) {
    console.error("Delete API error:", error);
    throw error;
  }
};
