// Auto-generated Pet service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Pet, CreatePetInput, UpdatePetInput } from "../types/index.js";

export class PetService {
  /** List all pets */
  list(): Pet[] {
    return queryAll<Pet>("SELECT * FROM pets ORDER BY created_at DESC");
  }

  /** Get by ID */
  getById(id: string): Pet | undefined {
    return queryOne<Pet>("SELECT * FROM pets WHERE id = ?", [id]);
  }

  /** Create */
  create(input: CreatePetInput): Pet {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "species", "breed", "birth_date", "weight_kg", "avatar_url", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.species ?? null, input.breed ?? null, input.birthDate ?? null, input.weightKg ?? null, input.avatarUrl ?? null, now, now];

    execute(`INSERT INTO pets (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
    return this.getById(id)!;
  }

  /** Update */
  update(id: string, input: UpdatePetInput): Pet | undefined {
    const existing = this.getById(id);
    if (!existing) return undefined;

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
    if (input.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
    if (input.species !== undefined) { sets.push("species = ?"); values.push(input.species); }
    if (input.breed !== undefined) { sets.push("breed = ?"); values.push(input.breed); }
    if (input.birthDate !== undefined) { sets.push("birth_date = ?"); values.push(input.birthDate); }
    if (input.weightKg !== undefined) { sets.push("weight_kg = ?"); values.push(input.weightKg); }
    if (input.avatarUrl !== undefined) { sets.push("avatar_url = ?"); values.push(input.avatarUrl); }

    if (sets.length === 0) return existing;

    sets.push("updated_at = ?");
    values.push(new Date().toISOString());

    values.push(id);
    execute(`UPDATE pets SET ${sets.join(", ")} WHERE id = ?`, values);
    return this.getById(id)!;
  }

  /** Delete */
  delete(id: string): boolean {
    const result = execute("DELETE FROM pets WHERE id = ?", [id]);
    return result.changes > 0;
  }
}
