import axios from 'axios';

const BACKEND_SERVER_URL = process.env.BACKEND_SERVER_URL;
const BACKEND_SITE_NAME = process.env.BACKEND_SITE_NAME;

export async function POST(request) {
  try {
    const body = await request.json();
    const { subject, content } = body;
    if (!subject || !content) {
      return Response.json({ error: 'Missing parameters: subject and content are required.' }, { status: 400 });
    }
    const response = await axios.post(
      `${BACKEND_SERVER_URL}/api/action/jsite.api.v1.send_email`,
      { subject, content, site_name: BACKEND_SITE_NAME }
    );
    const message = response.data.message;
    if (message?.success) {
      return Response.json({ success: true, message: message.message || 'Email sent successfully' });
    } else if (message?.error) {
      return Response.json({ error: message.error }, { status: 400 });
    } else {
      return Response.json({ error: 'Unknown error' }, { status: 500 });
    }
  } catch (error) {
    return Response.json(
      { error: error.message, detail: error?.response?.data || null },
      { status: 500 }
    );
  }
}
