// Auto-generated Stats service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Stats, CreateStatsInput, UpdateStatsInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateStatsInput): Stats {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "client_id", "service_id", "start_time", "end_time", "notes", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.clientId ?? null, input.serviceId ?? null, input.startTime ?? null, input.endTime ?? null, input.notes ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateStatsInput): Stats | 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.clientId !== undefined) { sets.push("client_id = ?"); values.push(input.clientId); }
    if (input.serviceId !== undefined) { sets.push("service_id = ?"); values.push(input.serviceId); }
    if (input.startTime !== undefined) { sets.push("start_time = ?"); values.push(input.startTime); }
    if (input.endTime !== undefined) { sets.push("end_time = ?"); values.push(input.endTime); }
    if (input.notes !== undefined) { sets.push("notes = ?"); values.push(input.notes); }

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

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

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

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