import { db, eq } from "@haushaltsApp/db";
import { shoppingListItems, shoppingLists } from "@haushaltsApp/db/schema";
import type { CreateShoppingListInput, CreateShoppingListItemInput } from "@haushaltsApp/shared/types";

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

export async function createShoppingList(input: CreateShoppingListInput) {
  const [list] = await db.insert(shoppingLists).values(input).returning();
  return list;
}

export async function addItemToList(userId: string, input: CreateShoppingListItemInput) {
  const [item] = await db
    .insert(shoppingListItems)
    .values({ ...input, addedByUserId: userId })
    .returning();
  return item;
}

export async function toggleItemChecked(id: string, userId: string, isChecked: boolean) {
  const [item] = await db
    .update(shoppingListItems)
    .set({
      isChecked,
      checkedByUserId: isChecked ? userId : null,
      checkedAt: isChecked ? new Date() : null,
    })
    .where(eq(shoppingListItems.id, id))
    .returning();
  return item;
}
