// Auto-generated Note service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Note, CreateNoteInput, UpdateNoteInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateNoteInput): Note {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = true;
    const hasUpdatedAt = true;
    const cols = ["id", "user_id", "title", "content", "is_markdown", "folder_id", "created_at", "updated_at"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.userId ?? null, input.title ?? null, input.content ?? null, input.isMarkdown ?? null, input.folderId ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateNoteInput): Note | 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.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
    if (input.content !== undefined) { sets.push("content = ?"); values.push(input.content); }
    if (input.isMarkdown !== undefined) { sets.push("is_markdown = ?"); values.push(input.isMarkdown); }
    if (input.folderId !== undefined) { sets.push("folder_id = ?"); values.push(input.folderId); }

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

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

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

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