import "server-only";
import { cookies } from "next/headers";
import { randomUUID } from "node:crypto";
import { prisma } from "@/lib/prisma";
import type { Locale } from "@/lib/i18n/config";
import { productCardInclude, translationFor } from "@/lib/catalog";
import { evaluateCoupon, type CouponResult } from "@/lib/coupons";
import { getSettings, type SettingsMap } from "@/lib/settings";
import { computeCartTotals } from "@/lib/cart-totals";
import { shippingConfig, shippingFor } from "@/lib/shipping";

export const CART_COOKIE = "dz_cart";
const THIRTY_DAYS = 60 * 60 * 24 * 30;

export type CartLine = {
  id: string;
  productId: string;
  variantId: string | null;
  slug: string;
  sku: string;
  name: string;
  variantName: string | null;
  image: string | null;
  imageAlt: string;
  unitPrice: number;
  lineTotal: number;
  quantity: number;
  stock: number;
  available: boolean;
};

export type CartView = {
  id: string;
  token: string;
  couponCode: string | null;
  items: CartLine[];
  subtotal: number;
  availableSubtotal: number;
  allAvailable: boolean;
};

export type CartSummary = {
  subtotal: number;
  discount: number;
  shipping: number;
  total: number;
  coupon: CouponResult | null;
  freeShipping: boolean;
};

export async function getCartToken() {
  const store = await cookies();
  return store.get(CART_COOKIE)?.value ?? null;
}

export async function setCartCookie(token: string) {
  const store = await cookies();
  store.set(CART_COOKIE, token, {
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    path: "/",
    maxAge: THIRTY_DAYS,
  });
}

export async function clearCartCookie() {
  const store = await cookies();
  store.delete(CART_COOKIE);
}

export async function ensureCart(userId?: string | null) {
  const owner = userId
    ? await prisma.user.findUnique({ where: { id: userId }, select: { id: true } })
    : null;
  const ownerId = owner?.id ?? null;
  const token = await getCartToken();
  if (token) {
    const existing = await prisma.cart.findUnique({ where: { token } });
    if (existing) {
      if (ownerId && !existing.userId) {
        return prisma.cart.update({ where: { id: existing.id }, data: { userId: ownerId } });
      }
      return existing;
    }
  }

  const newToken = randomUUID();
  const cart = await prisma.cart.create({ data: { token: newToken, userId: ownerId } });
  await setCartCookie(newToken);
  return cart;
}

export async function getCartView(locale: Locale): Promise<CartView | null> {
  const token = await getCartToken();
  if (!token) return null;

  const cart = await prisma.cart.findUnique({
    where: { token },
    include: {
      items: {
        orderBy: { createdAt: "asc" },
        include: {
          product: { include: productCardInclude },
          variant: true,
        },
      },
    },
  });
  if (!cart) return null;

  const items: CartLine[] = cart.items.map((item) => {
    const translation = translationFor(item.product.translations, locale);
    const unitPrice = item.product.price + (item.variant?.priceDelta ?? 0);
    const stock = item.variant ? Math.min(item.variant.stock, item.product.stock) : item.product.stock;
    const available = item.product.isPublished && stock >= item.quantity;
    return {
      id: item.id,
      productId: item.productId,
      variantId: item.variantId,
      slug: item.product.slug,
      sku: item.variant?.sku ?? item.product.sku,
      name: translation?.name ?? item.product.slug,
      variantName: item.variant?.name ?? null,
      image: item.product.images[0]?.url ?? null,
      imageAlt: item.product.images[0]?.alt ?? translation?.name ?? "",
      unitPrice,
      lineTotal: unitPrice * item.quantity,
      quantity: item.quantity,
      stock,
      available,
    };
  });

  const subtotal = items.reduce((sum, item) => sum + item.lineTotal, 0);
  const availableSubtotal = items
    .filter((item) => item.available)
    .reduce((sum, item) => sum + item.lineTotal, 0);

  return {
    id: cart.id,
    token: cart.token,
    couponCode: cart.couponCode,
    items,
    subtotal,
    availableSubtotal,
    allAvailable: items.every((item) => item.available),
  };
}

export async function getCartCount() {
  const token = await getCartToken();
  if (!token) return 0;
  const cart = await prisma.cart.findUnique({
    where: { token },
    select: { items: { select: { quantity: true } } },
  });
  return cart?.items.reduce((sum, item) => sum + item.quantity, 0) ?? 0;
}

export async function getCartSummary(
  cart: CartView | null,
  locale: Locale,
  country = "MA",
  settingsOverride?: SettingsMap,
): Promise<CartSummary> {
  if (!cart) {
    return { subtotal: 0, discount: 0, shipping: 0, total: 0, coupon: null, freeShipping: false };
  }

  const settings = settingsOverride ?? (await getSettings());
  const config = shippingConfig(settings);
  const shipping = cart.items.length > 0 ? shippingFor(country, cart.subtotal, config) : 0;

  let coupon: CouponResult | null = null;
  if (cart.couponCode) {
    const record = await prisma.coupon.findUnique({ where: { code: cart.couponCode } });
    coupon = evaluateCoupon(record, cart.subtotal);
  }

  const totals = computeCartTotals(cart.items, {
    discount: coupon?.ok ? coupon.discount : 0,
    shipping,
  });

  return {
    ...totals,
    coupon,
    freeShipping: shipping === 0 && cart.items.length > 0,
  };
}

export async function getCartForCheckout(locale: Locale) {
  const cart = await getCartView(locale);
  return cart;
}