import axios from 'axios';

const JINGROW_SERVER_URL = process.env.JINGROW_SERVER_URL;

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(
      `${JINGROW_SERVER_URL}/api/method/jsite.api.v1.send_email`,
      { subject, content }
    );
    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 }
    );
  }
}
