// Auto-generated Tag service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Tag, CreateTagInput, UpdateTagInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateTagInput): Tag {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "name", "color"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.name ?? null, input.color ?? null];

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

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

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
    if (input.color !== undefined) { sets.push("color = ?"); values.push(input.color); }

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

    

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

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