import { beforeAll, describe, expect, test } from "vitest";
import { createApp } from "~/server/app";
import { createTestSession, getAuthHeaders } from "~/test/helpers/auth";

const app = createApp();

let session: Awaited<ReturnType<typeof createTestSession>>;

beforeAll(async () => {
	session = await createTestSession();
});

describe("notifications security", () => {
	test("should return 401 if no session cookie is provided", async () => {
		const res = await app.request("/api/v1/notifications/destinations");
		expect(res.status).toBe(401);
		const body = await res.json();
		expect(body.message).toBe("Invalid or expired session");
	});

	test("should return 401 if session is invalid", async () => {
		const res = await app.request("/api/v1/notifications/destinations", {
			headers: getAuthHeaders("invalid-session"),
		});
		expect(res.status).toBe(401);
		const body = await res.json();
		expect(body.message).toBe("Invalid or expired session");
	});

	test("should return 200 if session is valid", async () => {
		const res = await app.request("/api/v1/notifications/destinations", {
			headers: session.headers,
		});

		expect(res.status).toBe(200);
	});

	describe("unauthenticated access", () => {
		const endpoints: { method: string; path: string }[] = [
			{ method: "GET", path: "/api/v1/notifications/destinations" },
			{ method: "POST", path: "/api/v1/notifications/destinations" },
			{ method: "GET", path: "/api/v1/notifications/destinations/1" },
			{ method: "PATCH", path: "/api/v1/notifications/destinations/1" },
			{ method: "DELETE", path: "/api/v1/notifications/destinations/1" },
			{ method: "POST", path: "/api/v1/notifications/destinations/1/test" },
		];

		for (const { method, path } of endpoints) {
			test(`${method} ${path} should return 401`, async () => {
				const res = await app.request(path, { method });
				expect(res.status).toBe(401);
				const body = await res.json();
				expect(body.message).toBe("Invalid or expired session");
			});
		}
	});

	describe("information disclosure", () => {
		test("should not disclose if a destination exists when unauthenticated", async () => {
			const res = await app.request("/api/v1/notifications/destinations/999999");
			expect(res.status).toBe(401);
			const body = await res.json();
			expect(body.message).toBe("Invalid or expired session");
		});
	});

	describe("input validation", () => {
		test("should return 404 for malformed destination ID", async () => {
			const res = await app.request("/api/v1/notifications/destinations/not-a-number", {
				headers: session.headers,
			});

			expect(res.status).toBe(404);
		});

		test("should return 404 for non-existent destination ID", async () => {
			const res = await app.request("/api/v1/notifications/destinations/999999", {
				headers: session.headers,
			});

			expect(res.status).toBe(404);
			const body = await res.json();
			expect(body.message).toBe("Notification destination not found");
		});

		test("should return 400 for invalid payload on create", async () => {
			const res = await app.request("/api/v1/notifications/destinations", {
				method: "POST",
				headers: {
					...session.headers,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					name: "Test",
				}),
			});

			expect(res.status).toBe(400);
		});

		test("should return 400 for notification webhook origins outside the allowlist", async () => {
			const res = await app.request("/api/v1/notifications/destinations", {
				method: "POST",
				headers: {
					...session.headers,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					name: "Blocked webhook",
					config: {
						type: "generic",
						url: "https://hooks.example.com/backup",
						method: "POST",
					},
				}),
			});

			expect(res.status).toBe(400);
			const body = await res.json();
			expect(body.message).toBe(
				"Notification webhook URL origin is not allowed. Add https://hooks.example.com to WEBHOOK_ALLOWED_ORIGINS.",
			);
		});

		test("should return 400 for custom shoutrrr network targets outside the allowlist", async () => {
			const res = await app.request("/api/v1/notifications/destinations", {
				method: "POST",
				headers: {
					...session.headers,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					name: "Blocked custom SMTP",
					config: {
						type: "custom",
						shoutrrrUrl: "smtp://127.0.0.1:2525/?from=test@example.com&to=admin@example.com",
					},
				}),
			});

			expect(res.status).toBe(400);
			const body = await res.json();
			expect(body.message).toBe(
				"Notification webhook URL origin is not allowed. Add smtp://127.0.0.1:2525 to WEBHOOK_ALLOWED_ORIGINS.",
			);
		});
	});
});
