export interface LoginRequest {
  account: string;
  password: string;
}

export interface RegisterRequest {
  account: string;
  password: string;
  name: string;
  email: string;
  phone?: string | null;
}

export interface UserResponse {
  id: string;
  account: string;
  name: string;
  email: string;
  phone?: string | null;
}

export interface TokenResponse {
  access_token: string;
  token_type: string;
  expires_at: string;
  user: UserResponse;
}

interface AuthErrorBody {
  message?: string;
  detail?: string | Record<string, string>;
}

async function postAuth<T>(path: string, body: unknown): Promise<T> {
  const response = await fetch(path, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest",
    },
    body: JSON.stringify(body),
  });

  let data: AuthErrorBody | T | null = null;
  try {
    data = (await response.json()) as AuthErrorBody | T;
  } catch {
    data = null;
  }

  if (!response.ok) {
    const error = data as AuthErrorBody | null;
    const detail = typeof error?.detail === "string" ? error.detail : error?.message;
    throw new Error(detail || "请求失败，请稍后重试");
  }

  return data as T;
}

export async function loginWithPassword(payload: LoginRequest): Promise<TokenResponse> {
  return postAuth<TokenResponse>("/auth/login", {
    account: payload.account.trim(),
    password: payload.password,
  });
}

export async function registerAccount(payload: RegisterRequest): Promise<TokenResponse> {
  return postAuth<TokenResponse>("/auth/register", {
    account: payload.account.trim(),
    password: payload.password,
    name: payload.name.trim(),
    email: payload.email.trim().toLowerCase(),
    phone: payload.phone?.trim() || null,
  });
}

export type { UserResponse as AuthUser };
