import { listMonths } from "@/lib/storage";
import { getSession } from "@/lib/auth/session";
import { canAccessBranch } from "@/lib/auth/permissions";
import {
	withErrorHandling,
	json,
	badRequest,
	unauthorized,
	forbidden,
} from "@/lib/api/errors";
import { mapStorageReadError } from "@/lib/api/storageErrors";

/**
 * Next.js Route Handler caching configuration (RHL-006):
 *
 * We force this route to execute dynamically on every request.
 *
 * Reasons:
 * - NAS contents can change at any time (new scans).
 * - Auth/RBAC-protected responses must not be cached/shared across users.
 * - We rely on a small storage-layer TTL micro-cache instead of Next route caching.
 */
export const dynamic = "force-dynamic";

/**
 * GET /api/branches/[branch]/[year]/months
 *
 * Happy-path response must remain unchanged:
 * { "branch": "NL01", "year": "2024", "months": ["10", ...] }
 */
export const GET = withErrorHandling(
	async function GET(request, ctx) {
		const session = await getSession();

		if (!session) {
			throw unauthorized("AUTH_UNAUTHENTICATED", "Unauthorized");
		}

		const { branch, year } = await ctx.params;

		// Validate required route params early.
		const missing = [];
		if (!branch) missing.push("branch");
		if (!year) missing.push("year");

		if (missing.length > 0) {
			throw badRequest(
				"VALIDATION_MISSING_PARAM",
				"Missing required route parameter(s)",
				{ params: missing }
			);
		}

		if (!canAccessBranch(session, branch)) {
			throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
		}

		try {
			const months = await listMonths(branch, year);
			return json({ branch, year, months }, 200);
		} catch (err) {
			throw await mapStorageReadError(err, { details: { branch, year } });
		}
	},
	{ logPrefix: "[api/branches/[branch]/[year]/months]" }
);
