// Auto-generated Services service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Services, CreateServicesInput, UpdateServicesInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateServicesInput): Services {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "description", "duration_min", "price", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.description ?? null, input.durationMin ?? null, input.price ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateServicesInput): Services | 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.description !== undefined) { sets.push("description = ?"); values.push(input.description); }
    if (input.durationMin !== undefined) { sets.push("duration_min = ?"); values.push(input.durationMin); }
    if (input.price !== undefined) { sets.push("price = ?"); values.push(input.price); }

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

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

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

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