"use server";

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

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

// ─────────────────────────────────────────────────────────
// Update Customer Profile
// ─────────────────────────────────────────────────────────
const updateProfileSchema = z.object({
  customerId: z.string().min(1),
  tenantSlug: z.string().min(1),
  driverLicenseNumber: z.string().optional(),
  driverLicenseExpiry: z.string().optional(),
  passportNumber: z.string().optional(),
  idNumber: z.string().optional(),
  nationality: z.string().optional(),
  city: z.string().optional(),
  country: z.string().optional(),
  addressLine1: z.string().optional(),
  notes: z.string().optional()
});

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

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

  const d = parsed.data;
  const tenant = await prisma.tenant.findUnique({where: {slug: d.tenantSlug}});
  if (!tenant) return {success: false, error: "Tenant not found"};

  try {
    const db = getTenantDb(tenant.id);
    await db.customerProfile.updateMany({
      where: {id: d.customerId},
      data: {
        driverLicenseNumber: d.driverLicenseNumber ?? null,
        driverLicenseExpiry: d.driverLicenseExpiry ? new Date(d.driverLicenseExpiry) : null,
        passportNumber: d.passportNumber ?? null,
        idNumber: d.idNumber ?? null,
        nationality: d.nationality ?? null,
        city: d.city ?? null,
        country: d.country ?? null,
        addressLine1: d.addressLine1 ?? null,
        notes: d.notes ?? null
      }
    });

    revalidatePath(`/company/${d.tenantSlug}/customers/${d.customerId}`);
    return {success: true};
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return {success: false, error: "Failed to update profile: " + message};
  }
}

// ─────────────────────────────────────────────────────────
// Blacklist Customer
// ─────────────────────────────────────────────────────────
export async function blacklistCustomer(customerId: string, tenantSlug: string): Promise<CustomerActionResult> {
  const session = await auth();
  if (!session?.user?.id) return {success: false, error: "Unauthorized"};

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) return {success: false, error: "Tenant not found"};

  try {
    const db = getTenantDb(tenant.id);
    await db.customerProfile.updateMany({
      where: {id: customerId},
      data: {blacklisted: true}
    });

    revalidatePath(`/company/${tenantSlug}/customers`);
    revalidatePath(`/company/${tenantSlug}/customers/${customerId}`);
    return {success: true};
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return {success: false, error: "Failed to blacklist customer: " + message};
  }
}

// ─────────────────────────────────────────────────────────
// Unblacklist Customer
// ─────────────────────────────────────────────────────────
export async function unblacklistCustomer(customerId: string, tenantSlug: string): Promise<CustomerActionResult> {
  const session = await auth();
  if (!session?.user?.id) return {success: false, error: "Unauthorized"};

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) return {success: false, error: "Tenant not found"};

  try {
    const db = getTenantDb(tenant.id);
    await db.customerProfile.updateMany({
      where: {id: customerId},
      data: {blacklisted: false}
    });

    revalidatePath(`/company/${tenantSlug}/customers`);
    revalidatePath(`/company/${tenantSlug}/customers/${customerId}`);
    return {success: true};
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return {success: false, error: "Failed to unblacklist customer: " + message};
  }
}

// ─────────────────────────────────────────────────────────
// Add Customer Note
// ─────────────────────────────────────────────────────────
export async function addCustomerNote(
  customerId: string,
  tenantSlug: string,
  note: string
): Promise<CustomerActionResult> {
  const session = await auth();
  if (!session?.user?.id) return {success: false, error: "Unauthorized"};

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) return {success: false, error: "Tenant not found"};

  try {
    const db = getTenantDb(tenant.id);
    const profile = await db.customerProfile.findFirst({where: {id: customerId}});
    if (!profile) return {success: false, error: "Customer not found"};

    const existingNotes = profile.notes ?? "";
    const timestamp = new Date().toLocaleDateString("en-US", {year: "numeric", month: "short", day: "numeric"});
    const newNotes = existingNotes
      ? `${existingNotes}\n\n[${timestamp}] ${note}`
      : `[${timestamp}] ${note}`;

    await db.customerProfile.updateMany({
      where: {id: customerId},
      data: {notes: newNotes}
    });

    revalidatePath(`/company/${tenantSlug}/customers/${customerId}`);
    return {success: true};
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return {success: false, error: "Failed to add note: " + message};
  }
}
