import type { APIRoute } from 'astro';
import jwt from 'jsonwebtoken';
import { sendEmail, escapeHtml } from '../../../utils/email-handler';
import fs from 'fs/promises';
import path from 'path';

const MANUAL_REVIEW_SECRET = process.env.MANUAL_REVIEW_SECRET;
const MANUAL_REVIEW_EMAIL = 'manual-review@365devnet.eu';

async function getTemplate(templateName: string, data: Record<string, string>): Promise<string> {
  const templatePath = path.join(process.cwd(), 'src', 'templates', 'email', `${templateName}.html`);
  let template = await fs.readFile(templatePath, 'utf-8');
  for (const key in data) {
    template = template.replace(new RegExp(`{{${key}}}`, 'g'), data[key]);
  }
  return template;
}

export const POST: APIRoute = async ({ request }) => {
  const { token, email: submittedEmail, justification } = await request.json();
  try {
    const payload = jwt.verify(token, MANUAL_REVIEW_SECRET) as { email: string, message: string };
    if (payload.email !== submittedEmail) {
      return new Response(JSON.stringify({ error: 'Email does not match original submission.' }), { status: 403 });
    }
    // Send to manual review mailbox
    const html = await getTemplate('manual-review', {
      email: escapeHtml(submittedEmail),
      message: escapeHtml(payload.message),
      justification: escapeHtml(justification || 'None provided'),
    });
    await sendEmail(
      MANUAL_REVIEW_EMAIL,
      'Manual Review Requested: Contact Form Submission',
      html,
      `Email: ${submittedEmail}\nMessage: ${payload.message}\nJustification: ${justification || 'None provided'}`
    );
    return new Response(JSON.stringify({ success: true }));
  } catch (_err) {
    return new Response(JSON.stringify({ error: 'Invalid or expired token.' }), { status: 400 });
  }
};


 