// Auto-generated Employees service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Employees, CreateEmployeesInput, UpdateEmployeesInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateEmployeesInput): Employees {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "email", "phone", "department", "position", "hire_date", "salary", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.email ?? null, input.phone ?? null, input.department ?? null, input.position ?? null, input.hireDate ?? null, input.salary ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateEmployeesInput): Employees | 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.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
    if (input.email !== undefined) { sets.push("email = ?"); values.push(input.email); }
    if (input.phone !== undefined) { sets.push("phone = ?"); values.push(input.phone); }
    if (input.department !== undefined) { sets.push("department = ?"); values.push(input.department); }
    if (input.position !== undefined) { sets.push("position = ?"); values.push(input.position); }
    if (input.hireDate !== undefined) { sets.push("hire_date = ?"); values.push(input.hireDate); }
    if (input.salary !== undefined) { sets.push("salary = ?"); values.push(input.salary); }

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

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

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

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