import { NextResponse } from 'next/server';

const GATEWAY = process.env.WHATSAPP_GATEWAY_URL;
const GROUP_URL = process.env.WHATSAPP_GROUP;
const PERSONAL_NUMBER = process.env.WHATSAPP_PERSONAL;

async function sendToRecipient(to, message) {
  const res = await fetch(GATEWAY, {
    method:  'POST',
    headers: { 'Content-Type': 'application/json' },
    body:    JSON.stringify({ to, message }),
  });
  return res.json();
}

export async function POST(request) {
  try {
    const { message, to, personalOnly } = await request.json();
    if (!message) {
      return NextResponse.json({ error: 'message is required' }, { status: 400 });
    }

    // personalOnly=true → only me; default → group + me
    const targets = personalOnly
      ? [{ to: PERSONAL_NUMBER, label: 'personal' }]
      : [
          { to: to || DEFAULT_GROUP, label: 'group'    },
          { to: PERSONAL_NUMBER,     label: 'personal' },
        ];

    const results = await Promise.allSettled(
      targets.map(t => sendToRecipient(t.to, message))
    );

    const successful = results.filter(r => r.status === 'fulfilled' && r.value?.success);
    const failed     = results.filter(r => r.status !== 'fulfilled' || !r.value?.success);

    if (successful.length === 0) {
      return NextResponse.json({ error: 'All recipients failed', details: failed }, { status: 502 });
    }

    return NextResponse.json({
      success:   true,
      sent:      successful.length,
      failed:    failed.length,
      messageId: successful[0]?.value?.messageId,
    });
  } catch (err) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
