"use server";

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

export type ContractActionResult = {success: boolean; error?: string; id?: string};

// ─────────────────────────────────────────────────────────
// Create Contract
// ─────────────────────────────────────────────────────────
const createContractSchema = z.object({
  bookingId: z.string().min(1),
  tenantId: z.string().min(1),
  contractNumber: z.string().min(1),
  customerName: z.string().min(1),
  customerPhone: z.string().min(1),
  customerIdNumber: z.string().min(1),
  licenseNumber: z.string().min(1),
  licenseExpiry: z.string().min(1),
  vehiclePlate: z.string().min(1),
  vehicleName: z.string().min(1),
  pickupLocation: z.string().min(1),
  dropoffLocation: z.string().min(1),
  pickupDate: z.string().min(1),
  dropoffDate: z.string().min(1),
  dailyRate: z.string().min(1),
  totalAmount: z.string().min(1),
  depositAmount: z.string().min(1),
  insuranceIncluded: z.string().optional(),
  notes: z.string().optional(),
  terms: z.string().optional()
});

export async function createContract(formData: FormData): Promise<ContractActionResult> {
  const session = await auth();
  if (!session?.user?.id) return {success: false, error: "Unauthorized"};

  const raw = Object.fromEntries(formData.entries());
  const parsed = createContractSchema.safeParse(raw);
  if (!parsed.success) {
    return {success: false, error: parsed.error.issues[0]?.message ?? "Validation error"};
  }

  const d = parsed.data;

  try {
    // Check if contract already exists for this booking
    const existing = await prisma.rentalContract.findUnique({where: {bookingId: d.bookingId}});
    if (existing) return {success: false, error: "A contract already exists for this booking"};

    const contract = await prisma.rentalContract.create({
      data: {
        tenantId: d.tenantId,
        bookingId: d.bookingId,
        contractNumber: d.contractNumber,
        customerName: d.customerName,
        customerPhone: d.customerPhone,
        customerIdNumber: d.customerIdNumber,
        licenseNumber: d.licenseNumber,
        licenseExpiry: new Date(d.licenseExpiry),
        vehiclePlate: d.vehiclePlate,
        vehicleName: d.vehicleName,
        pickupLocation: d.pickupLocation,
        dropoffLocation: d.dropoffLocation,
        pickupDate: new Date(d.pickupDate),
        dropoffDate: new Date(d.dropoffDate),
        dailyRate: parseFloat(d.dailyRate),
        totalAmount: parseFloat(d.totalAmount),
        depositAmount: parseFloat(d.depositAmount),
        insuranceIncluded: d.insuranceIncluded === "on" || d.insuranceIncluded === "true",
        notes: d.notes ?? null,
        terms: d.terms ?? null,
        status: "ACTIVE",
        signedAt: new Date(),
        createdById: session.user.id
      }
    });

    const slug = (await prisma.tenant.findUnique({where: {id: d.tenantId}, select: {slug: true}}))?.slug;
    revalidatePath(`/company/${slug}/contracts`);
    redirect(`/company/${slug}/contracts/${contract.id}`);
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Unknown error";
    if (message.includes("NEXT_REDIRECT")) throw err;
    return {success: false, error: "Failed to create contract: " + message};
  }
}

// ─────────────────────────────────────────────────────────
// Close Contract
// ─────────────────────────────────────────────────────────
export async function closeContract(contractId: string, tenantSlug: string): Promise<ContractActionResult> {
  const session = await auth();
  if (!session?.user?.id) return {success: false, error: "Unauthorized"};

  try {
    await prisma.rentalContract.update({
      where: {id: contractId},
      data: {status: "COMPLETED", closedAt: new Date(), actualReturnDate: new Date()}
    });
    revalidatePath(`/company/${tenantSlug}/contracts`);
    return {success: true};
  } catch {
    return {success: false, error: "Failed to close contract"};
  }
}

// ─────────────────────────────────────────────────────────
// Mark Contract as Overdue
// ─────────────────────────────────────────────────────────
export async function markContractOverdue(contractId: string, tenantSlug: string): Promise<ContractActionResult> {
  const session = await auth();
  if (!session?.user?.id) return {success: false, error: "Unauthorized"};

  try {
    await prisma.rentalContract.update({
      where: {id: contractId},
      data: {status: "OVERDUE"}
    });
    revalidatePath(`/company/${tenantSlug}/contracts`);
    return {success: true};
  } catch {
    return {success: false, error: "Failed to mark contract as overdue"};
  }
}

// ─────────────────────────────────────────────────────────
// Cancel Contract
// ─────────────────────────────────────────────────────────
export async function cancelContract(contractId: string, tenantSlug: string): Promise<ContractActionResult> {
  const session = await auth();
  if (!session?.user?.id) return {success: false, error: "Unauthorized"};

  try {
    await prisma.rentalContract.update({
      where: {id: contractId},
      data: {status: "CANCELLED", closedAt: new Date()}
    });
    revalidatePath(`/company/${tenantSlug}/contracts`);
    return {success: true};
  } catch {
    return {success: false, error: "Failed to cancel contract"};
  }
}
