import { db, eq, and } from "@haushaltsApp/db";
import { children } from "@haushaltsApp/db/schema";
import type { CreateChildInput, UpdateChildInput } from "@haushaltsApp/shared/schemas/children.schema";

export async function getChildren(householdId: string) {
  return db
    .select()
    .from(children)
    .where(eq(children.householdId, householdId))
    .orderBy(children.createdAt);
}

export async function getChildById(id: string, householdId: string) {
  const [child] = await db
    .select()
    .from(children)
    .where(and(eq(children.id, id), eq(children.householdId, householdId)));
  return child ?? null;
}

export async function createChild(householdId: string, input: CreateChildInput) {
  const [child] = await db
    .insert(children)
    .values({ householdId, name: input.name, color: input.color })
    .returning();
  return child;
}

export async function updateChild(id: string, householdId: string, input: UpdateChildInput) {
  const values: Partial<typeof input> = {};
  if (input.name !== undefined) values.name = input.name;
  if (input.color !== undefined) values.color = input.color;

  const [child] = await db
    .update(children)
    .set(values)
    .where(and(eq(children.id, id), eq(children.householdId, householdId)))
    .returning();
  return child ?? null;
}

export async function deleteChild(id: string, householdId: string) {
  const [child] = await db
    .delete(children)
    .where(and(eq(children.id, id), eq(children.householdId, householdId)))
    .returning();
  return child ?? null;
}
