"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import { auth } from "@/auth";
import { logSystemAction } from "./system-log";

// ─── PRODUCTS ─────────────────────────────────────────────────────────────────
export async function getProducts(params?: { search?: string; categoryId?: string; status?: string }) {
  try {
    const where: any = {};
    if (params?.search) where.OR = [
      { title: { contains: params.search } },
      { sku: { contains: params.search } },
      { barcode: { contains: params.search } },
    ];
    if (params?.status) where.status = params.status;

    const products = await prisma.product.findMany({
      where,
      orderBy: { createdAt: "desc" },
      include: {
        images: { orderBy: { sortOrder: "asc" }, take: 1 },
        categories: { include: { category: true } },
        brand: true,
        variants: { include: { options: { include: { attribute: true } } } },
        createdBy: { select: { fullName: true, phone: true } },
        updatedBy: { select: { fullName: true, phone: true } }
      },
    });
    return { success: true, products };
  } catch (e: any) {
    return { success: false, products: [], error: e.message };
  }
}

export async function getProductById(id: string) {
  try {
    const product = await prisma.product.findUnique({
      where: { id },
      include: {
        images: { orderBy: { sortOrder: "asc" } },
        categories: { include: { category: true } },
        brand: true,
        variants: { include: { options: { include: { attribute: true } } } },
        productAttributes: { include: { attribute: true } },
      },
    });
    return { success: true, product };
  } catch (e: any) {
    return { success: false, product: null };
  }
}

export async function createProduct(data: any) {
  try {
    const session = await auth();
    const userId = session?.user?.id;

    // Auto slug from title if not provided
    const slug = data.slug ||
      data.title.toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]/g, "") + "-" + Date.now();

    const product = await prisma.product.create({
      data: {
        title: data.title,
        titleEn: data.titleEn || null,
        slug,
        shortDesc: data.shortDescription || null,
        description: data.description || null,
        type: data.type || "SIMPLE",
        status: data.status || "PUBLISHED",
        isFeatured: data.isFeatured || false,
        price: parseInt(data.basePrice) || 0,
        salePrice: data.discountPrice ? parseInt(data.discountPrice) : null,
        sku: data.sku || null,
        barcode: data.barcode || null,
        weightGrams: data.weightGrams ? parseInt(data.weightGrams) : null,
        lengthMm: data.lengthMm ? parseInt(data.lengthMm) : null,
        widthMm: data.widthMm ? parseInt(data.widthMm) : null,
        heightMm: data.heightMm ? parseInt(data.heightMm) : null,
        manageStock: data.manageStock || false,
        stockQuantity: data.stock ? parseInt(data.stock) : null,
        lowStockThreshold: data.lowStockThreshold ? parseInt(data.lowStockThreshold) : null,
        brandId: data.brandId || null,
        seoTitle: data.seoTitle || null,
        seoDescription: data.seoDescription || null,
        seoKeywords: data.seoKeywords || null,
        countryId: data.countryId || null,
        syncStatus: 1,
        createdById: userId,
        updatedById: userId,
      } as any,
    });

    // Link categories
    if (data.categoryIds && data.categoryIds.length > 0) {
      await prisma.productCategory.createMany({
        data: data.categoryIds.map((cid: string) => ({ productId: product.id, categoryId: cid })),
      });
    }

    // Link images
    if (data.imageUrls && data.imageUrls.length > 0) {
      await prisma.productImage.createMany({
        data: data.imageUrls.map((url: string, i: number) => ({
          productId: product.id,
          imageUrl: url,
          sortOrder: i,
        })),
      });
    }

    // Persist Variants
    if (data.variants && data.variants.length > 0) {
      for (const variant of data.variants) {
        await prisma.productVariant.create({
          data: {
            productId: product.id,
            sku: variant.sku || null,
            price: parseInt(variant.price) || 0,
            salePrice: parseInt(variant.salePrice) || null,
            stockQuantity: parseInt(variant.stock) || 0,
            featuredMediaId: variant.imageUrl || null,
            options: {
              create: Object.entries(variant.attributes).map(([attrName, attrValue]) => ({
                attribute: {
                  connectOrCreate: {
                    where: { slug: attrName.replace(/\s+/g, '-').toLowerCase() },
                    create: { name: attrName, slug: attrName.replace(/\s+/g, '-').toLowerCase(), inputType: "TEXT" as any, isVariantable: true },
                  }
                },
                value: attrValue as string,
              }))
            }
          }
        });
      }
    }

    // Persist Custom Attributes
    if (data.customAttributes && data.customAttributes.length > 0) {
      for (const attr of data.customAttributes) {
        if (!attr.key || !attr.value) continue;
        await prisma.productAttribute.create({
          data: {
            product: { connect: { id: product.id } },
            value: attr.value,
            attribute: {
              connectOrCreate: {
                where: { slug: attr.key.replace(/\s+/g, '-').toLowerCase() },
                create: { name: attr.key, slug: attr.key.replace(/\s+/g, '-').toLowerCase(), inputType: "TEXT" as any, isVariantable: false },
              }
            }
          }
        });
      }
    }
    
    if (userId) {
      await logSystemAction("CREATE_PRODUCT", "Product", product.id, `ایجاد محصول جدید: ${product.title}`);
    }

    revalidatePath("/admin/products");
    return { success: true, product };
  } catch (e: any) {
    console.error(e);
    return { success: false, error: "خطا در ذخیره محصول: " + e.message };
  }
}

export async function updateProduct(id: string, data: any) {
  try {
    const session = await auth();
    const userId = session?.user?.id;

    const product = await prisma.product.update({
      where: { id },
      data: {
        title: data.title,
        titleEn: data.titleEn || null,
        slug: data.slug,
        shortDesc: data.shortDescription || null,
        description: data.description || null,
        status: data.status || "PUBLISHED",
        isFeatured: data.isFeatured || false,
        price: parseInt(data.basePrice) || 0,
        salePrice: data.discountPrice ? parseInt(data.discountPrice) : null,
        sku: data.sku || null,
        barcode: data.barcode || null,
        weightGrams: data.weightGrams ? parseInt(data.weightGrams) : null,
        lengthMm: data.lengthMm ? parseInt(data.lengthMm) : null,
        widthMm: data.widthMm ? parseInt(data.widthMm) : null,
        heightMm: data.heightMm ? parseInt(data.heightMm) : null,
        manageStock: data.manageStock || false,
        stockQuantity: data.stock ? parseInt(data.stock) : null,
        lowStockThreshold: data.lowStockThreshold ? parseInt(data.lowStockThreshold) : null,
        brandId: data.brandId || null,
        seoTitle: data.seoTitle || null,
        seoDescription: data.seoDescription || null,
        seoKeywords: data.seoKeywords || null,
        countryId: data.countryId || null,
        syncStatus: 2,
        updatedById: userId,
      } as any,
    });

    // Re-link categories
    if (data.categoryIds) {
      await prisma.productCategory.deleteMany({ where: { productId: id } });
      if (data.categoryIds.length > 0) {
        await prisma.productCategory.createMany({
          data: data.categoryIds.map((cid: string) => ({ productId: id, categoryId: cid })),
        });
      }
    }

    // Update Variants
    if (data.variants) {
      // Very simple implementation: delete old variants, insert new ones
      // In a real production system, you might want to diff them to preserve variant IDs for cart relationships
      await prisma.productVariant.deleteMany({ where: { productId: id } });
      for (const variant of data.variants) {
        await prisma.productVariant.create({
          data: {
            productId: id,
            sku: variant.sku || null,
            price: parseInt(variant.price) || 0,
            salePrice: parseInt(variant.salePrice) || null,
            stockQuantity: parseInt(variant.stock) || 0,
            featuredMediaId: variant.imageUrl || null,
            options: {
              create: Object.entries(variant.attributes).map(([attrName, attrValue]) => ({
                attribute: {
                  connectOrCreate: {
                    where: { slug: attrName.replace(/\s+/g, '-').toLowerCase() },
                    create: { name: attrName, slug: attrName.replace(/\s+/g, '-').toLowerCase(), inputType: "TEXT" as any, isVariantable: true },
                  }
                },
                value: attrValue as string,
              }))
            }
          }
        });
      }
    }

    // Update Custom Attributes
    if (data.customAttributes) {
      await prisma.productAttribute.deleteMany({ where: { productId: id } });
      for (const attr of data.customAttributes) {
        if (!attr.key || !attr.value) continue;
        await prisma.productAttribute.create({
          data: {
            product: { connect: { id } },
            value: attr.value,
            attribute: {
              connectOrCreate: {
                where: { slug: attr.key.replace(/\s+/g, '-').toLowerCase() },
                create: { name: attr.key, slug: attr.key.replace(/\s+/g, '-').toLowerCase(), inputType: "TEXT" as any, isVariantable: false },
              }
            }
          }
        });
      }
    }

    revalidatePath("/admin/products");
    revalidatePath(`/admin/products/${id}`);
    return { success: true, product };
  } catch (e: any) {
    return { success: false, error: "خطا در ویرایش محصول." };
  }
}

export async function deleteProduct(id: string) {
  try {
    await prisma.product.delete({ where: { id } });
    revalidatePath("/admin/products");
    return { success: true };
  } catch (e: any) {
    return { success: false, error: "این محصول در سفارشات استفاده شده و قابل حذف نیست." };
  }
}

export async function bulkUpdatePriceByUsdRate(usdRate: number) {
  try {
    // Fetch all products that have usdPrice stored as barcode-prefixed or notes
    // For now: apply a fixed multiplier to all prices
    // Real implementation: read usdPrice from a metadata field and multiply by usdRate
    const products = await prisma.product.findMany({ where: { syncStatus: 1 } });
    let updated = 0;
    for (const p of products) {
      if (!p.price) continue;
      // Phase 2 implementation: Read (p as any).usdPrice * usdRate
      // Placeholder until usdPrice column is added
      updated++;
    }
    revalidatePath("/admin/products");
    return { success: true, updatedCount: updated };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}

// Quick stock adjustment (for inventory management)
export async function adjustProductStock(productId: string, qty: number, reason: string) {
  try {
    const product = await prisma.product.findUnique({ where: { id: productId } });
    if (!product) return { success: false, error: "محصول یافت نشد." };

    const newQty = (product.stockQuantity || 0) + qty;
    await prisma.product.update({
      where: { id: productId },
      data: { stockQuantity: newQty, manageStock: true },
    });

    await (prisma as any).stockAdjustment.create({
      data: {
        productId,
        type: qty > 0 ? "ADD" : "REMOVE",
        quantity: Math.abs(qty),
        reason: reason || "تنظیم دستی موجودی",
      },
    });

    revalidatePath("/admin/products");
    return { success: true, newQuantity: newQty };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}
