import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, NotFoundError, ValidationError } from '@server/errors';
import { initDatabase } from '@server/db/init';
import { getDefaultTemplate } from '@server/services/email/templates';
import { renderTemplate } from '@server/services/email/render';

function requireAdmin(req: AuthedRequest) {
  if (req.session.role !== 'superadmin' && req.session.role !== 'support') throw new ForbiddenError();
}

const schema = z.object({
  subject: z.string().min(1),
  html: z.string().min(1),
});

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    requireAdmin(req);
    await initDatabase();
    const { key } = await ctx.params;
    const def = getDefaultTemplate(key);
    if (!def) throw new NotFoundError('Template');

    const body = await req.json();
    const parsed = schema.safeParse(body);
    if (!parsed.success) throw new ValidationError(parsed.error.issues[0]?.message || 'Invalid input');

    const preview = await renderTemplate(key, def.sampleVars ?? {}, null, {
      subject: parsed.data.subject,
      html: parsed.data.html,
    });

    return NextResponse.json({ subject: preview.subject, html: preview.html });
  })
);
