"use server";

import {auth} from "@/auth";
import {redirect} from "next/navigation";
import {prisma} from "@/lib/db/prisma";
import {z} from "zod";

const bookingSchema = z.object({
  vehicleId: z.string().min(1),
  pickupBranchId: z.string().min(1),
  dropoffBranchId: z.string().min(1),
  pickupAt: z.string().min(1),
  dropoffAt: z.string().min(1),
  firstName: z.string().min(1),
  lastName: z.string().min(1),
  phone: z.string().min(1),
  licenseNumber: z.string().optional(),
  notes: z.string().optional()
});

export type CreateBookingInput = z.infer<typeof bookingSchema>;
export type ActionResult = {success: false; error: string} | {success: true; bookingNumber: string};

export async function createBooking(input: CreateBookingInput): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user?.id) {
    return {success: false, error: "Not authenticated"};
  }

  const parsed = bookingSchema.safeParse(input);
  if (!parsed.success) {
    return {success: false, error: "Invalid booking data"};
  }

  const data = parsed.data;

  const vehicle = await prisma.vehicle.findFirst({
    where: {id: data.vehicleId, isPublic: true, status: "AVAILABLE"},
    include: {tenant: true}
  });

  if (!vehicle) {
    return {success: false, error: "Vehicle not available"};
  }

  const pickupDate = new Date(data.pickupAt);
  const dropoffDate = new Date(data.dropoffAt);
  const rentalMs = dropoffDate.getTime() - pickupDate.getTime();
  const rentalDays = Math.max(1, Math.ceil(rentalMs / (1000 * 60 * 60 * 24)));
  const dailyRate = Number(vehicle.dailyRate);
  const subtotal = rentalDays * dailyRate;
  const depositAmount = Number(vehicle.depositAmount);
  const totalAmount = subtotal + depositAmount;

  const year = new Date().getFullYear();
  const random = Math.random().toString(36).substring(2, 8).toUpperCase();
  const bookingNumber = `BK-${year}-${random}`;

  let customerProfile = await prisma.customerProfile.findFirst({
    where: {tenantId: vehicle.tenantId, userId: session.user.id}
  });

  if (!customerProfile) {
    customerProfile = await prisma.customerProfile.create({
      data: {
        tenantId: vehicle.tenantId,
        userId: session.user.id,
        driverLicenseNumber: data.licenseNumber ?? null
      }
    });
  }

  // Update user name if provided
  await prisma.user.update({
    where: {id: session.user.id},
    data: {
      firstName: data.firstName,
      lastName: data.lastName,
      phone: data.phone
    }
  });

  await prisma.booking.create({
    data: {
      tenantId: vehicle.tenantId,
      bookingNumber,
      source: "PUBLIC_WEB",
      status: "PENDING_APPROVAL",
      customerUserId: session.user.id,
      customerProfileId: customerProfile.id,
      vehicleId: vehicle.id,
      pickupBranchId: data.pickupBranchId,
      dropoffBranchId: data.dropoffBranchId,
      pickupAt: pickupDate,
      dropoffAt: dropoffDate,
      rentalDays,
      dailyRate,
      subtotal,
      depositAmount,
      totalAmount,
      currency: vehicle.tenant.currency,
      notes: data.notes ?? null
    }
  });

  return {success: true, bookingNumber};
}
