// Auto-generated ApprovalStep service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { ApprovalStep, CreateApprovalStepInput, UpdateApprovalStepInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateApprovalStepInput): ApprovalStep {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "approval_id", "approver_id", "step_order", "status", "comment", "acted_at"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.approvalId ?? null, input.approverId ?? null, input.stepOrder ?? null, input.status ?? null, input.comment ?? null, input.actedAt ?? null];

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

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

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.approvalId !== undefined) { sets.push("approval_id = ?"); values.push(input.approvalId); }
    if (input.approverId !== undefined) { sets.push("approver_id = ?"); values.push(input.approverId); }
    if (input.stepOrder !== undefined) { sets.push("step_order = ?"); values.push(input.stepOrder); }
    if (input.status !== undefined) { sets.push("status = ?"); values.push(input.status); }
    if (input.comment !== undefined) { sets.push("comment = ?"); values.push(input.comment); }
    if (input.actedAt !== undefined) { sets.push("acted_at = ?"); values.push(input.actedAt); }

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

    

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

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