// Auto-generated NoteTag service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { NoteTag, CreateNoteTagInput, UpdateNoteTagInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateNoteTagInput): NoteTag {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "note_id", "tag_id"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.noteId ?? null, input.tagId ?? null];

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

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

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.noteId !== undefined) { sets.push("note_id = ?"); values.push(input.noteId); }
    if (input.tagId !== undefined) { sets.push("tag_id = ?"); values.push(input.tagId); }

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

    

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

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