import { NextResponse } from 'next/server';
import { sql } from 'drizzle-orm';
import { db } from '@server/db/drizzle';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError } from '@server/errors';
import { initDatabase } from '@server/db/init';
import { DEFAULT_TEMPLATES } from '@server/services/email/render';

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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    requireAdmin(req);
    await initDatabase();
    const { rows } = await db.execute(sql`SELECT key, subject, html, updated_at FROM email_templates`);
    const overrideMap = new Map((rows as { key: string; subject: string; html: string; updated_at: string }[]).map(r => [r.key, r]));

    const items = DEFAULT_TEMPLATES.map(t => {
      const o = overrideMap.get(t.key);
      return {
        key: t.key,
        audience: t.audience,
        subject: o?.subject ?? t.subject,
        html: o?.html ?? t.body,
        defaultSubject: t.subject,
        defaultHtml: t.body,
        overridden: !!o,
        updatedAt: o?.updated_at ?? null,
      };
    });
    return NextResponse.json({ templates: items });
  })
);
