// Auto-generated Comments service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Comments, CreateCommentsInput, UpdateCommentsInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateCommentsInput): Comments {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "entity_type", "entity_id", "content", "parent_id", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.entityType ?? null, input.entityId ?? null, input.content ?? null, input.parentId ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateCommentsInput): Comments | 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.entityType !== undefined) { sets.push("entity_type = ?"); values.push(input.entityType); }
    if (input.entityId !== undefined) { sets.push("entity_id = ?"); values.push(input.entityId); }
    if (input.content !== undefined) { sets.push("content = ?"); values.push(input.content); }
    if (input.parentId !== undefined) { sets.push("parent_id = ?"); values.push(input.parentId); }

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

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

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

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