import { useAuth } from "@/store/auth";

export interface LoginInput {
  username: string;
  password: string;
}

/** OAuth2-shaped login response, extended with backend's 2FA signaling fields. */
export interface LoginOutput {
  access_token?: string | null;
  token_type: string;
  requires_2fa?: boolean;
  partial_token?: string | null;
}

export interface TwoFactorInput {
  partial_token: string;
  code: string;
  remember_device: boolean;
}

export async function login(input: LoginInput): Promise<LoginOutput> {
  const body = new URLSearchParams();
  body.set("username", input.username);
  body.set("password", input.password);
  // PWA — длинная сессия (30 дней) чтобы механики не вводили пароль каждые 8 ч.
  body.set("long_session", "true");

  const res = await fetch("/api/auth/login", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body,
    // Critical: include credentials so the 30-day trusted_device cookie is
    // sent back to backend on subsequent logins (lets us skip 2FA next time).
    credentials: "include",
  });
  if (!res.ok) {
    throw new Error(`Login failed: ${res.status}`);
  }
  return res.json();
}

export async function login2fa(input: TwoFactorInput): Promise<LoginOutput> {
  const res = await fetch("/api/auth/2fa", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ ...input, long_session: true }),
    credentials: "include",  // accept the trusted_device cookie on Set-Cookie
  });
  if (!res.ok) {
    throw new Error(`2FA failed: ${res.status}`);
  }
  return res.json();
}

export function logout(): void {
  useAuth.getState().setToken(null);
}
