import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { sendMail } from "@/lib/mail";

export async function POST(req: Request) {
  try {
    const body = await req.json();

    const fromCountryId = String(body.fromCountryId || "").trim();
    const fromCityId = String(body.fromCityId || "").trim();
    const toCountryId = String(body.toCountryId || "").trim();
    const toCityId = String(body.toCityId || "").trim();
    const tripTypeRaw = String(body.tripType || "one_way").trim();
    const departureDateRaw = String(body.departureDate || "").trim();
    const returnDateRaw = String(body.returnDate || "").trim();
    const passengers = Number(body.passengers || 1) || 1;
    const cabinClass = String(body.cabinClass || "").trim() || null;
    const name = String(body.name || "").trim();
    const email = String(body.email || "").trim().toLowerCase();
    const phone = String(body.phone || "").trim() || null;
    const message = String(body.message || "").trim() || null;

    if (!fromCountryId || !fromCityId || !toCountryId || !toCityId) {
      return NextResponse.json({ ok: false, error: "Please select route country and city." }, { status: 400 });
    }
    if (!name || !email) {
      return NextResponse.json({ ok: false, error: "Name and email are required." }, { status: 400 });
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json({ ok: false, error: "Please enter a valid email." }, { status: 400 });
    }

    const departureDate = new Date(departureDateRaw);
    if (!departureDateRaw || Number.isNaN(departureDate.getTime())) {
      return NextResponse.json({ ok: false, error: "Valid departure date is required." }, { status: 400 });
    }

    const tripType = tripTypeRaw === "return_trip" ? "return_trip" : "one_way";
    const returnDate = returnDateRaw ? new Date(returnDateRaw) : null;
    if (tripType === "return_trip") {
      if (!returnDate || Number.isNaN(returnDate.getTime())) {
        return NextResponse.json({ ok: false, error: "Return date is required for return trip." }, { status: 400 });
      }
      if (returnDate < departureDate) {
        return NextResponse.json({ ok: false, error: "Return date must be after departure date." }, { status: 400 });
      }
    }

    const [fromCountry, fromCity, toCountry, toCity] = await Promise.all([
      db.ticketCountry.findUnique({ where: { id: fromCountryId }, select: { id: true, name: true } }),
      db.ticketCity.findUnique({ where: { id: fromCityId }, select: { id: true, name: true, countryId: true } }),
      db.ticketCountry.findUnique({ where: { id: toCountryId }, select: { id: true, name: true } }),
      db.ticketCity.findUnique({ where: { id: toCityId }, select: { id: true, name: true, countryId: true } }),
    ]);

    if (!fromCountry || !fromCity || !toCountry || !toCity) {
      return NextResponse.json({ ok: false, error: "Invalid route selected." }, { status: 400 });
    }

    if (fromCity.countryId !== fromCountry.id || toCity.countryId !== toCountry.id) {
      return NextResponse.json({ ok: false, error: "Selected city does not match country." }, { status: 400 });
    }

    const session = await auth();

    await db.ticketRequest.create({
      data: {
        userId: session?.user?.id || null,
        fromCountryId,
        fromCityId,
        toCountryId,
        toCityId,
        tripType,
        departureDate,
        returnDate: tripType === "return_trip" ? returnDate : null,
        passengers,
        cabinClass,
        name,
        email,
        phone,
        message,
        status: "new",
      },
    });

    const adminEmailSetting = await db.siteSetting.findUnique({ where: { key: "admin_email" } });
    const adminEmail = (adminEmailSetting?.value || process.env.ADMIN_EMAIL || "").trim();

    if (adminEmail) {
      const routeLine = `${fromCity.name}, ${fromCountry.name} -> ${toCity.name}, ${toCountry.name}`;
      const dateLine =
        tripType === "return_trip" && returnDate
          ? `${departureDate.toISOString().slice(0, 10)} to ${returnDate.toISOString().slice(0, 10)}`
          : departureDate.toISOString().slice(0, 10);

      await sendMail({
        to: adminEmail,
        subject: `New Ticket Request - ${name}`,
        html: `
          <h2>New Ticket Booking Request</h2>
          <p><strong>Customer:</strong> ${name} (${email})</p>
          <p><strong>Phone:</strong> ${phone || "-"}</p>
          <p><strong>Route:</strong> ${routeLine}</p>
          <p><strong>Trip Type:</strong> ${tripType === "return_trip" ? "Return" : "One Way"}</p>
          <p><strong>Date:</strong> ${dateLine}</p>
          <p><strong>Passengers:</strong> ${passengers}</p>
          <p><strong>Cabin Class:</strong> ${cabinClass || "-"}</p>
          <p><strong>Message:</strong><br/>${(message || "-").replace(/\n/g, "<br/>")}</p>
        `,
      });
    }

    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ ok: false, error: "Failed to submit ticket request." }, { status: 500 });
  }
}
