import { z } from "zod/v4";
import type { EmailsIdEmail } from "~/schemas/public/Emails";
import {
	adminProcedure,
	createTRPCRouter,
	protectedProcedure,
} from "~/server/api/trpc";
import { db } from "~/server/db";
import {
	deleteAllUserEmails,
	deleteEmail,
	getEmails,
} from "~/server/services/email.service";
import { NewMail } from "~/server/services/mailer";
import { zAnnuncioId, zUserId } from "~/server/utils/zod_types";

export const comunicazioniRouter = createTRPCRouter({
	// genEmail: publicProcedure
	// 	.input(
	// 		z.object({
	// 			mail: z.custom<MailsTemplates>(),
	// 		}),
	// 	)
	// 	.query(async ({ input }) => {
	// 		return await genMail({
	// 			...input.mail,
	// 		});
	// 	}),
	getEmails: protectedProcedure
		.input(z.object({ userId: zUserId }))
		.query(async ({ input }) => {
			return await getEmails({
				userId: input.userId,
			});
		}),
	deleteEmail: adminProcedure
		.input(
			z.object({
				id_email: z.custom<EmailsIdEmail>(),
			}),
		)
		.mutation(async ({ input }) => {
			return await deleteEmail({
				id_email: input.id_email,
			});
		}),
	deleteAllUserEmails: adminProcedure
		.input(z.object({ userId: zUserId }))
		.mutation(async ({ input }) => {
			return await deleteAllUserEmails({
				userId: input.userId,
			});
		}),
	sendSchedaAnnuncioEmail: adminProcedure
		.input(
			z.object({
				pdf: z.string(),
				codice: z.string(),
				numero: z.string(),
				nominativo: z.string(),
				indirizzo: z.string(),
				to: z.email(),
			}),
		)
		.mutation(async ({ input }) => {
			try {
				const base64Content = input.pdf.includes("base64,")
					? input.pdf.split("base64,")[1]
					: input.pdf;

				await NewMail({
					template: {
						mailType: "emailSchedaContatto",
						props: {
							nominativo: input.nominativo,
							telefono: input.numero,
							indirizzo: input.indirizzo,
						},
					},
					mail: {
						subject: `Scheda Annuncio ${input.codice} - Infoalloggi.it`,
						to: input.to,
						attachments: [
							{
								filename: `scheda annuncio ${input.codice}.pdf`,
								content: base64Content,
								encoding: "base64",
								contentType: "application/pdf",
							},
						],
					},
				});

				await NewMail({
					template: {
						mailType: "generic",
						props: {
							title: `Ricevuta invio Scheda ${input.codice} a ${input.to}`,
							testo: `La scheda dell'annuncio ${input.codice} è stata inviata a ${input.to} con successo.`,
						},
					},
					mail: {
						subject: `Ricevuta invio Scheda ${input.codice} a ${input.to}`,
						to: "web@infoalloggi.it",
					},
				});
			} catch (e) {
				throw new Error(
					`Errore nell'invio dell'email: ${(e as Error).message}`,
				);
			}
		}),
	sendAnnunciEmail: adminProcedure
		.input(
			z.object({
				annunci: zAnnuncioId.array(),
				to: z.email(),
			}),
		)
		.mutation(async ({ input }) => {
			try {
				const annunci = await db
					.selectFrom("annunci")
					.select([
						"annunci.titolo_it as titolo",
						"annunci.codice",
						"annunci.prezzo",
					])
					.innerJoin("images_refs", "images_refs.codice", "annunci.codice")
					.select("images_refs.img as immagine")
					.where("images_refs.ordine", "=", 0)
					.where("annunci.id", "in", input.annunci)
					.execute();
				console.log(annunci);
				await NewMail({
					template: {
						mailType: "shareAnnunci",
						props: {
							nome: "Admin",
							annunci,
						},
					},
					mail: {
						subject: `Scheda Annuncio - Infoalloggi.it`,
						to: input.to,
					},
				});
			} catch (e) {
				throw new Error(
					`Errore nell'invio dell'email: ${(e as Error).message}`,
				);
			}
		}),
});
