import { db, eq, and, sql } from "@haushaltsApp/db";
import { categories, transactions } from "@haushaltsApp/db/schema";

const DEFAULT_CATEGORIES = [
  { name: "Lebensmittel", color: "#10b981", type: "expense" as const },
  { name: "Wohnen", color: "#6366f1", type: "expense" as const },
  { name: "Transport", color: "#f59e0b", type: "expense" as const },
  { name: "Gesundheit", color: "#ef4444", type: "expense" as const },
  { name: "Freizeit", color: "#8b5cf6", type: "expense" as const },
  { name: "Kinder", color: "#ec4899", type: "expense" as const },
  { name: "Urlaub", color: "#0ea5e9", type: "expense" as const },
  { name: "Sonstiges", color: "#6b7280", type: "expense" as const },
  { name: "Gehalt", color: "#10b981", type: "income" as const },
  { name: "Sonstiges Einkommen", color: "#6b7280", type: "income" as const },
] as const;

export async function seedDefaultCategories(householdId: string) {
  const rows = DEFAULT_CATEGORIES.map((cat) => ({
    householdId,
    name: cat.name,
    color: cat.color,
    type: cat.type,
    isDefault: true,
  }));
  return db.insert(categories).values(rows).returning();
}

export async function getCategoriesByHousehold(householdId: string) {
  return db.select().from(categories).where(eq(categories.householdId, householdId));
}

export async function createCategory(householdId: string, data: { name: string; icon?: string | null; color?: string | null; type: "income" | "expense" }) {
  const [cat] = await db.insert(categories).values({
    householdId,
    name: data.name,
    icon: data.icon ?? null,
    color: data.color ?? null,
    type: data.type,
    isDefault: false,
  }).returning();
  return cat;
}

export async function updateCategory(householdId: string, categoryId: string, data: { name?: string; icon?: string | null; color?: string | null }) {
  const [cat] = await db.update(categories)
    .set({ ...(data.name ? { name: data.name } : {}), icon: data.icon, color: data.color })
    .where(and(eq(categories.id, categoryId), eq(categories.householdId, householdId)))
    .returning();
  return cat ?? null;
}

export async function deleteCategory(householdId: string, categoryId: string): Promise<{ deleted: boolean; usageCount: number }> {
  // Check if any transactions use this category
  const usageCount = await db.select({ count: sql<number>`count(*)::int` }).from(transactions)
    .where(and(eq(transactions.householdId, householdId), eq(transactions.categoryId, categoryId)));
  const count = usageCount[0]?.count ?? 0;
  if (count > 0) {
    return { deleted: false, usageCount: count };
  }
  await db.delete(categories).where(and(eq(categories.id, categoryId), eq(categories.householdId, householdId), eq(categories.isDefault, false)));
  return { deleted: true, usageCount: 0 };
}
