import "server-only";
import { randomBytes } from "node:crypto";
import { prisma } from "@/lib/prisma";
import { getSettings } from "@/lib/settings";
import { shippingConfig, shippingFor } from "@/lib/shipping";
import { evaluateCoupon } from "@/lib/coupons";
import { translationFor } from "@/lib/catalog";
import { computeCartTotals } from "@/lib/cart-totals";

export class OrderError extends Error {
  code: "EMPTY_CART" | "OUT_OF_STOCK" | "COUPON_INVALID" | "UNKNOWN";
  constructor(code: OrderError["code"], message: string) {
    super(message);
    this.code = code;
  }
}

export type PlaceOrderInput = {
  cartToken: string;
  userId?: string | null;
  locale: string;
  paymentMethod: string;
  customerName: string;
  email: string;
  phone: string;
  country: string;
  city: string;
  addressLine1: string;
  addressLine2?: string;
  postalCode?: string;
  notes?: string;
};

export function generateOrderReference(now = new Date()) {
  return `DZ-${now.getFullYear()}-${randomBytes(3).toString("hex").toUpperCase()}`;
}

export async function placeOrder(input: PlaceOrderInput) {
  const settings = await getSettings();
  const config = shippingConfig(settings);

  const order = await prisma.$transaction(
    async (tx) => {
      const cart = await tx.cart.findUnique({
        where: { token: input.cartToken },
        include: {
          items: {
            include: {
              product: { include: { translations: true, images: { orderBy: { position: "asc" } } } },
              variant: true,
            },
          },
        },
      });

      if (!cart || cart.items.length === 0) {
        throw new OrderError("EMPTY_CART", "Votre panier est vide.");
      }

      let subtotal = 0;
      const prepared = cart.items.map((item) => {
        const translation = translationFor(item.product.translations, input.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;
        if (!item.product.isPublished || stock < item.quantity) {
          throw new OrderError("OUT_OF_STOCK", `La pièce « ${translation?.name ?? item.product.slug} » n'est plus disponible en quantité suffisante.`);
        }
        subtotal += unitPrice * item.quantity;
        return {
          item,
          translation,
          unitPrice,
          lineTotal: unitPrice * item.quantity,
        };
      });

      let discount = 0;
      let couponId: string | null = null;
      if (cart.couponCode) {
        const coupon = await tx.coupon.findUnique({ where: { code: cart.couponCode } });
        const result = evaluateCoupon(coupon, subtotal);
        if (result.ok && coupon) {
          discount = result.discount;
          couponId = coupon.id;
          if (coupon.maxUses !== null && coupon.usedCount >= coupon.maxUses) {
            throw new OrderError("COUPON_INVALID", "Ce code a atteint sa limite d'utilisation.");
          }
        }
      }

      const shipping = shippingFor(input.country, subtotal, config);
      const totals = computeCartTotals(
        prepared.map((line) => ({ unitPrice: line.unitPrice, quantity: line.item.quantity })),
        { discount, shipping },
      );

      const reference = generateOrderReference();

      for (const line of prepared) {
        const { item } = line;
        const productUpdate = await tx.product.updateMany({
          where: { id: item.productId, stock: { gte: item.quantity } },
          data: { stock: { decrement: item.quantity } },
        });
        if (productUpdate.count !== 1) {
          throw new OrderError("OUT_OF_STOCK", "Une pièce vient d'être épuisée. Merci de mettre à jour votre panier.");
        }

        if (item.variantId) {
          const variantUpdate = await tx.productVariant.updateMany({
            where: { id: item.variantId, stock: { gte: item.quantity } },
            data: { stock: { decrement: item.quantity } },
          });
          if (variantUpdate.count !== 1) {
            throw new OrderError("OUT_OF_STOCK", "Une option choisie n'est plus disponible.");
          }
        }

        await tx.inventoryMovement.create({
          data: {
            productId: item.productId,
            variantId: item.variantId,
            type: "SALE",
            quantity: -item.quantity,
            previousStock: item.product.stock,
            newStock: item.product.stock - item.quantity,
            reason: `Commande ${reference}`,
            orderId: reference,
          },
        });
      }

      const created = await tx.order.create({
        data: {
          reference,
          userId: input.userId ?? cart.userId ?? null,
          status: "PENDING",
          paymentMethod: input.paymentMethod,
          paymentStatus: "PENDING",
          customerName: input.customerName,
          email: input.email,
          phone: input.phone,
          country: input.country,
          city: input.city,
          addressLine1: input.addressLine1,
          addressLine2: input.addressLine2 || null,
          postalCode: input.postalCode || null,
          notes: input.notes || null,
          subtotal: totals.subtotal,
          discount: totals.discount,
          shipping: totals.shipping,
          total: totals.total,
          currency: "MAD",
          locale: input.locale,
          couponCode: couponId ? cart.couponCode : null,
          items: {
            create: prepared.map((line) => ({
              productId: line.item.productId,
              variantId: line.item.variantId,
              name: line.translation?.name ?? line.item.product.slug,
              variantName: line.item.variant?.name ?? null,
              sku: line.item.variant?.sku ?? line.item.product.sku,
              image: line.item.product.images[0]?.url ?? null,
              unitPrice: line.unitPrice,
              quantity: line.item.quantity,
              total: line.lineTotal,
            })),
          },
        },
        include: { items: true },
      });

      if (couponId) {
        await tx.coupon.update({ where: { id: couponId }, data: { usedCount: { increment: 1 } } });
      }

      await tx.cartItem.deleteMany({ where: { cartId: cart.id } });
      await tx.cart.delete({ where: { id: cart.id } });

      if (input.userId) {
        const addressCount = await tx.customerAddress.count({ where: { userId: input.userId } });
        if (addressCount === 0) {
          await tx.customerAddress.create({
            data: {
              userId: input.userId,
              label: "Livraison",
              fullName: input.customerName,
              phone: input.phone,
              country: input.country,
              city: input.city,
              addressLine1: input.addressLine1,
              addressLine2: input.addressLine2 || null,
              postalCode: input.postalCode || null,
              isDefault: true,
            },
          });
        }
      }

      return created;
    },
    { timeout: 20_000 },
  );

  return order;
}

export async function restockCancelledOrder(orderId: string) {
  return prisma.$transaction(async (tx) => {
    const order = await tx.order.findUnique({ where: { id: orderId }, include: { items: true } });
    if (!order || order.status === "CANCELLED") return null;

    for (const item of order.items) {
      if (!item.productId) continue;
      const product = await tx.product.findUnique({ where: { id: item.productId } });
      if (!product) continue;

      await tx.product.update({
        where: { id: item.productId },
        data: { stock: { increment: item.quantity } },
      });
      if (item.variantId) {
        await tx.productVariant.update({
          where: { id: item.variantId },
          data: { stock: { increment: item.quantity } },
        }).catch(() => null);
      }

      await tx.inventoryMovement.create({
        data: {
          productId: item.productId,
          variantId: item.variantId,
          type: "CANCELLATION",
          quantity: item.quantity,
          previousStock: product.stock,
          newStock: product.stock + item.quantity,
          reason: `Annulation ${order.reference}`,
          orderId: order.reference,
        },
      });
    }

    return order;
  });
}

export async function getOrderByReference(reference: string) {
  return prisma.order.findUnique({
    where: { reference },
    include: { items: true },
  });
}

export async function getUserOrders(userId: string) {
  return prisma.order.findMany({
    where: { userId },
    orderBy: { createdAt: "desc" },
    include: { items: true },
  });
}
