
const API_URL = process.env.NEXT_PUBLIC_API_URL?.replace(/\/+$/, "");

export type LoginResponse = {
  message?: string | string[];
  user?: {
    id: string;
    name: string;
    email: string;
    mobile: string;
    role: string;
    status: string;
  };
  accessToken?: string;
  [key: string]: unknown;
};

type LoginCredentials = {
  identifier: string;
  password: string;
};

export async function loginUser(
  credentials: LoginCredentials,
): Promise<LoginResponse> {
  if (!API_URL) {
    throw new Error(
      "Login service is not configured. Set NEXT_PUBLIC_API_URL.",
    );
  }

  const identifier = credentials.identifier.trim();

  if (!identifier) {
    throw new Error("Email or mobile is required.");
  }

  if (!credentials.password) {
    throw new Error("Password is required.");
  }

  let response: Response;

  try {
    response = await fetch(`${API_URL}/api/v1/auth/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      credentials: "include",
      body: JSON.stringify({
        identifier,
        password: credentials.password,
      }),
    });
  } catch {
    throw new Error(
      "Unable to connect to the server. Please try again.",
    );
  }

  const result: LoginResponse = await response
    .json()
    .catch(() => ({} as LoginResponse));

  if (!response.ok) {
    const message = Array.isArray(result.message)
      ? result.message.join(", ")
      : result.message;

    throw new Error(
      message || `Login failed (${response.status}).`,
    );
  }

  if (!result.user) {
    throw new Error(
      "Login response did not contain user information.",
    );
  }

  return result;
}

export async function logoutUser(): Promise<void> {
  if (!API_URL) {
    throw new Error(
      "Logout service is not configured. Set NEXT_PUBLIC_API_URL.",
    );
  }

  let response: Response;

  try {
    response = await fetch(`${API_URL}/api/v1/auth/logout`, {
      method: "POST",
      credentials: "include",
      cache: "no-store",
    });
  } catch {
    throw new Error("Unable to connect to the server. Please try again.");
  }

  if (!response.ok) {
    const result: LoginResponse = await response
      .json()
      .catch(() => ({} as LoginResponse));
    const message = Array.isArray(result.message)
      ? result.message.join(", ")
      : result.message;

    throw new Error(message || `Logout failed (${response.status}).`);
  }
}
