/**
 * WhatsApp Bookings API
 * POST /api/whatsapp/bookings
 *
 * Creates appointment bookings from WhatsApp conversations.
 * Called by n8n workflow AI agent tool.
 */

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireFeatureAccess } from "@/lib/services/whatsapp-feature-access.service";
import { isSlotAvailable } from "@/lib/services/whatsapp-availability.service";
import { BookingCreateSchema } from "@/lib/validators/whatsapp-ai.validator";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { logger } from "@/lib/logger";
import { convexMutation } from "@/lib/convex-client";
import { corsResponse } from "@/lib/cors";

export async function POST(request: NextRequest) {
  try {
    // Authenticate caller via n8n token
    const authHeader = request.headers.get("authorization");
    const token = authHeader?.replace("Bearer ", "");
    if (!token) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const isValid = await systemSettingsService.validateN8NToken(token);
    if (!isValid) {
      return NextResponse.json({ error: "Invalid token" }, { status: 401 });
    }

    const body = await request.json();

    // Validate input
    const validation = BookingCreateSchema.safeParse(body);
    if (!validation.success) {
      return NextResponse.json(
        { error: "Invalid request", details: validation.error.errors },
        { status: 400 },
      );
    }
    const input = validation.data;

    // Resolve organization owner
    const organization = await prisma.organizations.findUnique({
      where: { id: input.organizationId },
      select: { ownerId: true },
    });
    if (!organization) {
      return NextResponse.json(
        {
          error: "Organization not found",
          message: "The organization does not exist.",
        },
        { status: 404 },
      );
    }

    const booking = await convexMutation("bookings/mutations:create", {
      userId: organization.ownerId,
      customerName: input.customerName ?? "",
      customerPhone: input.customerPhone,
      customerEmail: input.customerEmail ?? "",
      service: "General Consultation",
      appointmentDate: new Date(input.appointmentDate).getTime(),
      appointmentTime: new Date(input.appointmentDate)
        .toISOString()
        .split("T")[1]
        .substring(0, 5),
      duration: input.duration,
      totalAmount: 0,
      notes: input.notes,
      source: "whatsapp",
    });

    return NextResponse.json({
      booking,
      message: "Booking confirmed",
      success: true,
    });
  } catch (error) {
    logger.error("Booking creation error", { error });

    return NextResponse.json(
      {
        error: "Internal server error",
        message:
          error instanceof Error ? error.message : "Failed to create booking",
      },
      { status: 500 },
    );
  }
}

// OPTIONS for CORS preflight
export async function OPTIONS() {
  return corsResponse("POST, OPTIONS");
}
