import { prisma } from '@/lib/prisma';
import { sanitizeText } from '@/lib/sanitize';
import type { CreateProductInput, UpdateProductInput, UpdateRecipeInput, CreateCategoryInput } from '@/schemas/product.schema';

// ─── CATEGORÍAS ───────────────────────────────────────────────────────────────

export async function listCategories() {
  return prisma.category.findMany({
    where: { isActive: true },
    orderBy: { name: 'asc' },
    include: { _count: { select: { products: true } } },
  });
}

export async function createCategory(data: CreateCategoryInput) {
  return prisma.category.create({
    data: { name: sanitizeText(data.name), isDrink: data.isDrink },
  });
}

export async function updateCategory(id: string, data: Partial<CreateCategoryInput>) {
  return prisma.category.update({
    where: { id },
    data: {
      ...(data.name ? { name: sanitizeText(data.name) } : {}),
      ...(data.isDrink !== undefined ? { isDrink: data.isDrink } : {}),
    },
  });
}

export async function deleteCategory(id: string) {
  return prisma.category.update({ where: { id }, data: { isActive: false } });
}

// ─── PRODUCTOS ────────────────────────────────────────────────────────────────

export async function listProducts(filters?: { categoryId?: string; type?: string; isAvailable?: boolean; page?: number; limit?: number }) {
  const page = filters?.page || 1;
  const limit = filters?.limit || 20;
  const skip = (page - 1) * limit;

  const where = {
    ...(filters?.categoryId ? { categoryId: filters.categoryId } : {}),
    ...(filters?.type ? { type: filters.type as never } : {}),
    ...(filters?.isAvailable !== undefined ? { isAvailable: filters.isAvailable } : {}),
  };

  const [products, total] = await prisma.$transaction([
    prisma.product.findMany({
      where,
      skip,
      take: limit,
      include: { category: { select: { id: true, name: true } } },
      orderBy: { name: 'asc' },
    }),
    prisma.product.count({ where }),
  ]);

  return { products, total, page, limit };
}

export async function getProductById(id: string) {
  return prisma.product.findUnique({
    where: { id },
    include: {
      category: true,
      recipeItems: {
        include: { ingredient: { select: { id: true, name: true, unitMeasure: true } } },
      },
      stocks: {
        include: { warehouse: { select: { id: true, name: true } } },
      },
    },
  });
}

export async function createProduct(data: CreateProductInput) {
  return prisma.product.create({
    data: {
      sku: data.sku ? sanitizeText(data.sku) : undefined,
      name: sanitizeText(data.name),
      description: data.description ? sanitizeText(data.description) : undefined,
      type: data.type,
      unitMeasure: data.unitMeasure,
      price: data.price,
      cost: data.cost,
      isAvailable: data.isAvailable,
      requiresAgeVer: data.requiresAgeVer,
      categoryId: data.categoryId,
    },
    include: { category: { select: { id: true, name: true } } },
  });
}

export async function updateProduct(id: string, data: UpdateProductInput) {
  return prisma.product.update({
    where: { id },
    data: {
      ...(data.sku !== undefined ? { sku: sanitizeText(data.sku) } : {}),
      ...(data.name ? { name: sanitizeText(data.name) } : {}),
      ...(data.description !== undefined ? { description: sanitizeText(data.description) } : {}),
      ...(data.type ? { type: data.type } : {}),
      ...(data.unitMeasure ? { unitMeasure: data.unitMeasure } : {}),
      ...(data.price !== undefined ? { price: data.price } : {}),
      ...(data.cost !== undefined ? { cost: data.cost } : {}),
      ...(data.isAvailable !== undefined ? { isAvailable: data.isAvailable } : {}),
      ...(data.requiresAgeVer !== undefined ? { requiresAgeVer: data.requiresAgeVer } : {}),
      ...(data.categoryId ? { categoryId: data.categoryId } : {}),
    },
    include: { category: { select: { id: true, name: true } } },
  });
}

export async function deleteProduct(id: string) {
  return prisma.product.update({ where: { id }, data: { isAvailable: false } });
}

// ─── RECETAS ──────────────────────────────────────────────────────────────────

export async function updateProductRecipe(productId: string, data: UpdateRecipeInput) {
  return prisma.$transaction(async (tx) => {
    // Verificar que el producto sea de tipo receta
    const product = await tx.product.findUnique({ where: { id: productId }, select: { type: true } });
    if (!product) throw new Error('PRODUCT_NOT_FOUND');
    if (product.type !== 'RECIPE_COCKTAIL') throw new Error('INVALID_STATUS: Solo productos tipo RECIPE_COCKTAIL pueden tener receta');

    // Eliminar ingredientes actuales y recrear
    await tx.recipeItem.deleteMany({ where: { productId } });
    await tx.recipeItem.createMany({
      data: data.items.map((item) => ({
        productId,
        ingredientId: item.ingredientId,
        quantity: item.quantity,
        unitMeasure: item.unitMeasure,
      })),
    });

    return tx.product.findUnique({
      where: { id: productId },
      include: {
        recipeItems: { include: { ingredient: { select: { id: true, name: true, unitMeasure: true } } } },
      },
    });
  });
}
