// Auto-generated Reminder service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Reminder, CreateReminderInput, UpdateReminderInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateReminderInput): Reminder {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "entity_type", "entity_id", "remind_at", "message", "sent", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.entityType ?? null, input.entityId ?? null, input.remindAt ?? null, input.message ?? null, input.sent ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateReminderInput): Reminder | 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.entityType !== undefined) { sets.push("entity_type = ?"); values.push(input.entityType); }
    if (input.entityId !== undefined) { sets.push("entity_id = ?"); values.push(input.entityId); }
    if (input.remindAt !== undefined) { sets.push("remind_at = ?"); values.push(input.remindAt); }
    if (input.message !== undefined) { sets.push("message = ?"); values.push(input.message); }
    if (input.sent !== undefined) { sets.push("sent = ?"); values.push(input.sent); }

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

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

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

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