import { API_URL } from "./config"

const E2E_API_URL = API_URL

const DEFAULT_PASSWORD = "E2eTestPass123"

export interface TestUser {
	id: string
	username: string
	email: string
	firstName: string
	lastName: string
	password: string
	accessToken: string
	refreshToken: string
}

interface IRegisterTestUserOptions {
	firstName?: string
	lastName?: string
	password?: string
}

export const registerTestUser = async (
	options?: IRegisterTestUserOptions,
): Promise<TestUser> => {
	const suffix =
		Date.now().toString(36) + Math.random().toString(36).slice(2, 6)
	const username = `e2e_${suffix}`
	const firstName = options?.firstName ?? "E2E"
	const lastName = options?.lastName ?? "Test"
	const password = options?.password ?? DEFAULT_PASSWORD
	const email = `${username}@test.local`

	const response = await fetch(`${E2E_API_URL}/auth/register`, {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({
			username,
			email,
			password,
			first_name: firstName,
			last_name: lastName,
		}),
	})

	if (!response.ok) {
		throw new Error(
			`Register failed: ${response.status} ${await response.text()}`,
		)
	}

	const data = await response.json()

	return {
		id: data.user.id,
		username: data.user.username,
		email,
		firstName,
		lastName,
		password,
		accessToken: data.access,
		refreshToken: data.refresh,
	}
}

/* ------------------------------------------------------------------ */
/*  Admin helpers (shared by upload / silence / etc. fixtures)          */
/* ------------------------------------------------------------------ */

export interface AuthTokens {
	accessToken: string
	refreshToken: string
}

export async function loginAsAdmin(): Promise<AuthTokens> {
	const res = await fetch(`${E2E_API_URL}/auth/login`, {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({ username: "admin", password: "admin" }),
	})

	if (!res.ok) {
		throw new Error(`Admin login failed: ${res.status} ${await res.text()}`)
	}

	const data = await res.json()
	return {
		accessToken: data.access,
		refreshToken: data.refresh,
	}
}

export async function createProjectViaApi(
	token: string,
	name: string,
): Promise<string> {
	const res = await fetch(`${E2E_API_URL}/api/projects/`, {
		method: "POST",
		headers: {
			"Content-Type": "application/json",
			Authorization: `Bearer ${token}`,
		},
		body: JSON.stringify({ name, language: "auto" }),
	})

	if (!res.ok) {
		throw new Error(
			`Create project failed: ${res.status} ${await res.text()}`,
		)
	}

	const data = await res.json()
	return data.id
}

export async function deleteProjectViaApi(
	token: string,
	projectId: string,
): Promise<void> {
	const res = await fetch(`${E2E_API_URL}/api/projects/${projectId}/`, {
		method: "DELETE",
		headers: { Authorization: `Bearer ${token}` },
	})
	if (!res.ok && res.status !== 404) {
		throw new Error(`Delete project failed: ${res.status}`)
	}
}

export { DEFAULT_PASSWORD as TEST_USER_PASSWORD, E2E_API_URL }
