import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";
import { sendMessage } from "@/lib/waha";

export async function POST(req: Request) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { phone, message } = await req.json();
  if (!phone || !message) {
    return NextResponse.json({ error: "Phone and message are required" }, { status: 400 });
  }

  // Log message
  const log = await prisma.messageLog.create({
    data: {
      clinicId: session.id,
      phone,
      direction: "outgoing",
      message,
      status: "queued",
    },
  });

  // Send via Waha
  try {
    const result = await sendMessage(phone, message);
    await prisma.messageLog.update({
      where: { id: log.id },
      data: {
        status: "sent",
        wahaMessageId: result?.key?.id || null,
        sentAt: new Date(),
      },
    });
    return NextResponse.json({ ok: true, id: log.id });
  } catch (err) {
    await prisma.messageLog.update({
      where: { id: log.id },
      data: { status: "failed" },
    });
    return NextResponse.json({ ok: false, error: String(err) }, { status: 500 });
  }
}
