import { createCookieSessionStorage } from "react-router";
import crypto from "crypto";
//#region app/clients/backend-client.server.ts
var BackendClient = class {
	async isOnboarding() {
		const url = process.env.BACKEND_URL + "/api/is-onboarding";
		const response = await fetch(url, {
			method: "GET",
			headers: {
				"Content-Type": "application/json",
				"x-api-key": process.env.FRONTEND_BACKEND_API_KEY || ""
			}
		});
		if (!response.ok) throw new Error(`Failed to fetch onboarding status: ${(await response.json()).error}`);
		return (await response.json()).isOnboarding;
	}
	async createAccount(username, password) {
		const url = process.env.BACKEND_URL + "/api/create-account";
		const response = await fetch(url, {
			method: "POST",
			headers: { "x-api-key": process.env.FRONTEND_BACKEND_API_KEY || "" },
			body: (() => {
				const form = new FormData();
				form.append("username", username);
				form.append("password", password);
				form.append("type", "admin");
				return form;
			})()
		});
		if (!response.ok) throw new Error(`Failed to create account: ${(await response.json()).error}`);
		return (await response.json()).status;
	}
	async authenticate(username, password) {
		const url = process.env.BACKEND_URL + "/api/authenticate";
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, {
			method: "POST",
			headers: { "x-api-key": apiKey },
			body: (() => {
				const form = new FormData();
				form.append("username", username);
				form.append("password", password);
				form.append("type", "admin");
				return form;
			})()
		});
		if (!response.ok) throw new Error(`Failed to authenticate: ${(await response.json()).error}`);
		return (await response.json()).authenticated;
	}
	async getQueue(limit) {
		const url = process.env.BACKEND_URL + `/api?mode=queue&limit=${limit}`;
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, { headers: { "x-api-key": apiKey } });
		if (!response.ok) throw new Error(`Failed to get queue: ${(await response.json()).error}`);
		return (await response.json()).queue;
	}
	async getHistory(limit) {
		const url = process.env.BACKEND_URL + `/api?mode=history&pageSize=${limit}`;
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, { headers: { "x-api-key": apiKey } });
		if (!response.ok) throw new Error(`Failed to get history: ${(await response.json()).error}`);
		return (await response.json()).history;
	}
	async addNzb(nzbFile) {
		var category = (await this.getConfig(["api.manual-category"])).find((item) => item.configName === "api.manual-category")?.configValue || "uncategorized";
		const url = process.env.BACKEND_URL + `/api?mode=addfile&cat=${category}&priority=0&pp=0`;
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, {
			method: "POST",
			headers: { "x-api-key": apiKey },
			body: (() => {
				const form = new FormData();
				form.append("nzbFile", nzbFile, nzbFile.name);
				return form;
			})()
		});
		if (!response.ok) throw new Error(`Failed to add nzb file: ${(await response.json()).error}`);
		const data = await response.json();
		if (!data.nzo_ids || data.nzo_ids.length != 1) throw new Error(`Failed to add nzb file: unexpected response format`);
		return data.nzo_ids[0];
	}
	async listWebdavDirectory(directory) {
		const url = process.env.BACKEND_URL + "/api/list-webdav-directory";
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, {
			method: "POST",
			headers: { "x-api-key": apiKey },
			body: (() => {
				const form = new FormData();
				form.append("directory", directory);
				return form;
			})()
		});
		if (!response.ok) throw new Error(`Failed to list webdav directory: ${(await response.json()).error}`);
		return (await response.json()).items;
	}
	async getConfig(keys) {
		const url = process.env.BACKEND_URL + "/api/get-config";
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, {
			method: "POST",
			headers: { "x-api-key": apiKey },
			body: (() => {
				const form = new FormData();
				for (const key of keys) form.append("config-keys", key);
				return form;
			})()
		});
		if (!response.ok) throw new Error(`Failed to get config items: ${(await response.json()).error}`);
		return (await response.json()).configItems || [];
	}
	async updateConfig(configItems) {
		const url = process.env.BACKEND_URL + "/api/update-config";
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, {
			method: "POST",
			headers: { "x-api-key": apiKey },
			body: (() => {
				const form = new FormData();
				for (const item of configItems) form.append(item.configName, item.configValue);
				return form;
			})()
		});
		if (!response.ok) throw new Error(`Failed to update config items: ${(await response.json()).error}`);
		return (await response.json()).status;
	}
	async getHealthCheckQueue(pageSize) {
		let url = process.env.BACKEND_URL + "/api/get-health-check-queue";
		if (pageSize !== void 0) url += `?pageSize=${pageSize}`;
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, {
			method: "GET",
			headers: { "x-api-key": apiKey }
		});
		if (!response.ok) throw new Error(`Failed to get health check queue: ${(await response.json()).error}`);
		return await response.json();
	}
	async getHealthCheckHistory(pageSize) {
		let url = process.env.BACKEND_URL + "/api/get-health-check-history";
		if (pageSize !== void 0) url += `?pageSize=${pageSize}`;
		const apiKey = process.env.FRONTEND_BACKEND_API_KEY || "";
		const response = await fetch(url, {
			method: "GET",
			headers: { "x-api-key": apiKey }
		});
		if (!response.ok) throw new Error(`Failed to get health check history: ${(await response.json()).error}`);
		return await response.json();
	}
};
var backendClient = new BackendClient();
//#endregion
//#region app/auth/authentication.server.ts
var IS_FRONTEND_AUTH_DISABLED = process.env.DISABLE_FRONTEND_AUTH === "true";
var sessionStorage = createCookieSessionStorage({ cookie: {
	name: "__session",
	httpOnly: true,
	path: "/",
	sameSite: "strict",
	secrets: [process?.env?.SESSION_KEY || crypto.randomBytes(64).toString("hex")],
	secure: ["true", "yes"].includes(process?.env?.SECURE_COOKIES || ""),
	maxAge: 3600 * 24 * 365
} });
async function isAuthenticated(request) {
	if (IS_FRONTEND_AUTH_DISABLED) return true;
	const cookieHeader = request instanceof Request ? request.headers.get("cookie") : request.headers.cookie;
	if (!cookieHeader) return false;
	return !!(await sessionStorage.getSession(cookieHeader)).get("user");
}
async function login(request) {
	let user = await authenticate(request);
	let session = await sessionStorage.getSession(request.headers.get("cookie"));
	session.set("user", user);
	return { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } };
}
async function logout(request) {
	let session = await sessionStorage.getSession(request.headers.get("cookie"));
	session.unset("user");
	return { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } };
}
async function setSessionUser(request, username) {
	let session = await sessionStorage.getSession(request.headers.get("cookie"));
	session.set("user", { username });
	return { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } };
}
async function authenticate(request) {
	const formData = await request.formData();
	const username = formData.get("username")?.toString();
	const password = formData.get("password")?.toString();
	if (!username || !password) throw new Error("username and password required");
	if (await backendClient.authenticate(username, password)) return { username };
	throw new Error("Invalid credentials");
}
//#endregion
export { setSessionUser as a, logout as i, isAuthenticated as n, backendClient as o, login as r, IS_FRONTEND_AUTH_DISABLED as t };
