// Auto-generated InspectionPlans service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { InspectionPlans, CreateInspectionPlansInput, UpdateInspectionPlansInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateInspectionPlansInput): InspectionPlans {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "frequency", "equipment_id", "next_run", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.frequency ?? null, input.equipmentId ?? null, input.nextRun ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateInspectionPlansInput): InspectionPlans | 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.frequency !== undefined) { sets.push("frequency = ?"); values.push(input.frequency); }
    if (input.equipmentId !== undefined) { sets.push("equipment_id = ?"); values.push(input.equipmentId); }
    if (input.nextRun !== undefined) { sets.push("next_run = ?"); values.push(input.nextRun); }

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

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

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

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