// Auto-generated Attendance service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Attendance, CreateAttendanceInput, UpdateAttendanceInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateAttendanceInput): Attendance {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "user_id", "check_in_at", "check_out_at", "location", "type"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.userId ?? null, input.checkInAt ?? null, input.checkOutAt ?? null, input.location ?? null, input.type ?? null];

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

  /** Update */
  update(id: string, input: UpdateAttendanceInput): Attendance | 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.checkInAt !== undefined) { sets.push("check_in_at = ?"); values.push(input.checkInAt); }
    if (input.checkOutAt !== undefined) { sets.push("check_out_at = ?"); values.push(input.checkOutAt); }
    if (input.location !== undefined) { sets.push("location = ?"); values.push(input.location); }
    if (input.type !== undefined) { sets.push("type = ?"); values.push(input.type); }

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

    

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

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