import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
import { env } from "~/env";
import { adminProcedure, createTRPCRouter } from "~/server/api/trpc";
import { getCodici_AnnunciHandler } from "~/server/controllers/annunci.controller";
import {
	getCacheStats,
	invalidateAllCaches,
} from "~/server/services/cache.service";
import {
	revalidate,
	revalidateMultiple,
} from "~/server/utils/revalidationHelper";

export const revalidationRouter = createTRPCRouter({
	revalidateAllAnnunci: adminProcedure.mutation(async () => {
		try {
			const annunciOnline = await getCodici_AnnunciHandler();
			const { success, failed } = await revalidateMultiple(
				annunciOnline.map((cod) => `/annuncio/${cod}`),
			);
			//console.log(`Successfully revalidated pages: ${success.join(", ")}`);
			if (success.length === 0) {
				console.log("No annunci were revalidated.");
			}
			if (failed.length > 0) {
				failed.forEach(({ path, error }) => {
					console.error(`Failed to revalidate ${path}: ${error}`);
				});
			}
			return {
				status: "success",
			};
		} catch (err) {
			console.error("Revalidation error:", err);
			throw new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: err instanceof Error ? err.message : "Revalidation failed",
				cause: err,
			});
		}
	}),
	revalidateAnnuncio: adminProcedure
		.input(
			z.object({
				cod: z.string(),
			}),
		)
		.mutation(async ({ input }) => {
			try {
				await revalidate(`/annuncio/${input.cod}`);
				return {
					status: "success",
				};
			} catch (err) {
				console.error("Revalidation error:", err);
				throw new TRPCError({
					code: "INTERNAL_SERVER_ERROR",
					message: err instanceof Error ? err.message : "Revalidation failed",
					cause: err,
				});
			}
		}),

	updateAllAnnunci: adminProcedure.mutation(async () => {
		try {
			const response = await fetch(`${env.BACKENDSERVER_URL}/update`);

			if (!response.ok) {
				const errorData = await response.text().catch(() => "Unknown error");
				throw new Error(
					`Update failed with status ${response.status}: ${errorData}`,
				);
			}

			const data = await response.json().catch(() => ({}));
			const annunciOnline = await getCodici_AnnunciHandler();
			const { success, failed } = await revalidateMultiple(
				annunciOnline.map((cod) => `/annuncio/${cod}`),
			);
			if (success.length === 0) {
				console.log("No annunci were revalidated.");
			}
			//console.log(`Successfully revalidated pages: ${success.join(", ")}`);
			if (failed.length > 0) {
				failed.forEach(({ path, error }) => {
					console.error(`Failed to revalidate ${path}: ${error}`);
				});
			}
			return {
				status: "success",
				details: data,
			};
		} catch (err) {
			console.error("Update error:", err);
			throw new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: err instanceof Error ? err.message : "Update failed",
				cause: err,
			});
		}
	}),
	updateAnnuncio: adminProcedure
		.input(
			z.object({
				cod: z.string(),
			}),
		)
		.mutation(async ({ input }) => {
			try {
				const response = await fetch(
					`${env.BACKENDSERVER_URL}/update-cod/${input.cod}`,
				);

				if (!response.ok) {
					const errorData = await response.text().catch(() => "Unknown error");
					throw new Error(
						`Update failed with status ${response.status}: ${errorData}`,
					);
				}

				const data = await response.json().catch(() => ({}));
				await revalidate(`/annuncio/${input.cod}`);
				return {
					status: "success",
					details: data,
				};
			} catch (err) {
				console.error("Update error:", err);
				throw new TRPCError({
					code: "INTERNAL_SERVER_ERROR",
					message: err instanceof Error ? err.message : "Update failed",
					cause: err,
				});
			}
		}),
	getRedisStats: adminProcedure.query(async () => {
		return await getCacheStats();
	}),
	invalidateRedisCache: adminProcedure.mutation(async () => {
		try {
			await invalidateAllCaches();
			return {
				status: "success",
			};
		} catch (err) {
			console.error("Invalidate Redis cache error:", err);
			throw new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message:
					err instanceof Error ? err.message : "Invalidate Redis cache failed",
				cause: err,
			});
		}
	}),
});
