// Auto-generated Tasks service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Tasks, CreateTasksInput, UpdateTasksInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateTasksInput): Tasks {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "board_id", "title", "description", "due_date", "assignee_id", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.boardId ?? null, input.title ?? null, input.description ?? null, input.dueDate ?? null, input.assigneeId ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateTasksInput): Tasks | 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.boardId !== undefined) { sets.push("board_id = ?"); values.push(input.boardId); }
    if (input.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
    if (input.description !== undefined) { sets.push("description = ?"); values.push(input.description); }
    if (input.dueDate !== undefined) { sets.push("due_date = ?"); values.push(input.dueDate); }
    if (input.assigneeId !== undefined) { sets.push("assignee_id = ?"); values.push(input.assigneeId); }

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

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

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

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