import { APIRequestContext } from "@playwright/test";

export const API_URL = process.env.E2E_API_URL ?? "http://127.0.0.1:8001";

export function uniqueEmail(prefix: string): string {
  return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@example.com`;
}

export async function registerUser(request: APIRequestContext, email: string, password = "Valid1234") {
  const response = await request.post(`${API_URL}/api/v1/auth/register`, {
    data: { email, password }
  });
  return response;
}

export async function fetchLatestToken(
  request: APIRequestContext,
  email: string,
  template: "verify_email" | "reset_password"
): Promise<string> {
  const response = await request.get(`${API_URL}/api/v1/test/emails/latest-token`, {
    params: { to: email, template }
  });
  if (!response.ok()) {
    throw new Error(`Token not found for ${email} (${template})`);
  }
  const body = await response.json();
  return body.token as string;
}

export async function verifyEmail(request: APIRequestContext, email: string) {
  const token = await fetchLatestToken(request, email, "verify_email");
  return request.post(`${API_URL}/api/v1/auth/verify-email`, { data: { token } });
}

export async function loginApi(request: APIRequestContext, email: string, password = "Valid1234") {
  return request.post(`${API_URL}/api/v1/auth/login`, { data: { email, password } });
}

export async function adminLogin(request: APIRequestContext) {
  return loginApi(request, "admin@compton.example", "Admin1234");
}

export async function registerVerifyLogin(
  request: APIRequestContext,
  email: string,
  password = "Valid1234"
) {
  await registerUser(request, email, password);
  await verifyEmail(request, email);
  const login = await loginApi(request, email, password);
  const body = await login.json();
  return {
    accessToken: body.access_token as string,
    user: body.user as { id: string; email: string; role: string; status: string }
  };
}

export async function loginViaUi(page: import("@playwright/test").Page, email: string, password: string) {
  await page.goto("/login");
  await page.getByPlaceholder("Email").fill(email);
  await page.getByPlaceholder("Password").fill(password);
  await page.getByRole("button", { name: "Login" }).click();
}
