// Auto-generated Articles service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Articles, CreateArticlesInput, UpdateArticlesInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateArticlesInput): Articles {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "title", "content", "excerpt", "cover_url", "author_id", "category", "published_at", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.title ?? null, input.content ?? null, input.excerpt ?? null, input.coverUrl ?? null, input.authorId ?? null, input.category ?? null, input.publishedAt ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateArticlesInput): Articles | 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.excerpt !== undefined) { sets.push("excerpt = ?"); values.push(input.excerpt); }
    if (input.coverUrl !== undefined) { sets.push("cover_url = ?"); values.push(input.coverUrl); }
    if (input.authorId !== undefined) { sets.push("author_id = ?"); values.push(input.authorId); }
    if (input.category !== undefined) { sets.push("category = ?"); values.push(input.category); }
    if (input.publishedAt !== undefined) { sets.push("published_at = ?"); values.push(input.publishedAt); }

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

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

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

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