// Auto-generated Department service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Department, CreateDepartmentInput, UpdateDepartmentInput } from "../types/index.js";

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

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

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

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

  /** Update */
  update(id: string, input: UpdateDepartmentInput): Department | 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.parentId !== undefined) { sets.push("parent_id = ?"); values.push(input.parentId); }
    if (input.managerId !== undefined) { sets.push("manager_id = ?"); values.push(input.managerId); }

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

    

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

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