import { z } from "zod/v4";
import type { EmailsIdEmail } from "~/schemas/public/Emails";
import {
	adminProcedure,
	createTRPCRouter,
	protectedProcedure,
} from "~/server/api/trpc";
import { DeleteEmail, GetEmails } from "~/server/services/email.service";
import { NewMail } from "~/server/services/mailer";
import { 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,
			});
		}),
	// storeEmail: publicProcedure
	// 	.input(
	// 		z.object({
	// 			data: z.custom<MailsTemplates>(),
	// 			userId: zUserId,
	// 		}),
	// 	)
	// 	.mutation(async ({ input }) => {
	// 		return await StoreEmail({
	// 			data: input.data,
	// 			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",
							},
						],
					},
				});
			} catch (e) {
				throw new Error(
					`Errore nell'invio dell'email: ${(e as Error).message}`,
				);
			}
		}),
});
