"use server";

import { createClient } from "@/lib/supabase/server";
import { revalidatePath } from "next/cache";

export async function getProducts(search?: string) {
  const supabase = await createClient();
  let query = supabase.from("products").select("*, stock:inventory_stock(current_stock)").eq("is_active", true).order("name");
  if (search) query = query.or(`name.ilike.%${search}%,sku.ilike.%${search}%`);
  const { data, error } = await query;
  if (error) throw error;
  return data;
}

export async function getProduct(id: string) {
  const supabase = await createClient();
  const { data, error } = await supabase.from("products").select("*, stock:inventory_stock(current_stock)").eq("id", id).single();
  if (error) throw error;
  return data;
}

export async function createProduct(formData: FormData) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) throw new Error("No autenticado");
  const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
  if (!profile) throw new Error("Perfil no encontrado");

  const { error } = await supabase.from("products").insert({
    clinic_id: profile.clinic_id,
    name: formData.get("name") as string,
    sku: (formData.get("sku") as string) || null,
    description: (formData.get("description") as string) || null,
    category: (formData.get("category") as string) || "insumo",
    unit: (formData.get("unit") as string) || "pieza",
    purchase_price: parseFloat(formData.get("purchase_price") as string) || 0,
    sale_price: parseFloat(formData.get("sale_price") as string) || 0,
    min_stock: parseInt(formData.get("min_stock") as string) || 0,
  });
  if (error) throw error;
  revalidatePath("/inventory");
}

export async function createMovement(data: { product_id: string; type: string; quantity: number; reason?: string }) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) throw new Error("No autenticado");
  const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
  if (!profile) throw new Error("Perfil no encontrado");

  const qty = data.type === "salida" || data.type === "merma" ? -Math.abs(data.quantity) : Math.abs(data.quantity);

  const { error } = await supabase.from("inventory_movements").insert({
    clinic_id: profile.clinic_id,
    product_id: data.product_id,
    type: data.type,
    quantity: qty,
    reason: data.reason || null,
    created_by: user.id,
  });
  if (error) throw error;
  revalidatePath("/inventory");
}

export async function getMovements(productId?: string) {
  const supabase = await createClient();
  let query = supabase
    .from("inventory_movements")
    .select("*, product:products(id, name, sku)")
    .order("created_at", { ascending: false })
    .limit(100);
  if (productId) query = query.eq("product_id", productId);
  const { data, error } = await query;
  if (error) throw error;
  return data;
}

export async function getLowStockProducts() {
  const supabase = await createClient();
  const { data: products } = await supabase.from("products").select("*, stock:inventory_stock(current_stock)").eq("is_active", true);
  if (!products) return [];
  return products.filter((p: any) => {
    const stock = p.stock?.[0]?.current_stock || 0;
    return stock <= p.min_stock;
  });
}
