// Auto-generated FollowUps service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { FollowUps, CreateFollowUpsInput, UpdateFollowUpsInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateFollowUpsInput): FollowUps {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "customer_id", "type", "content", "next_action", "next_action_date", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.customerId ?? null, input.type ?? null, input.content ?? null, input.nextAction ?? null, input.nextActionDate ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateFollowUpsInput): FollowUps | 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.customerId !== undefined) { sets.push("customer_id = ?"); values.push(input.customerId); }
    if (input.type !== undefined) { sets.push("type = ?"); values.push(input.type); }
    if (input.content !== undefined) { sets.push("content = ?"); values.push(input.content); }
    if (input.nextAction !== undefined) { sets.push("next_action = ?"); values.push(input.nextAction); }
    if (input.nextActionDate !== undefined) { sets.push("next_action_date = ?"); values.push(input.nextActionDate); }

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

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

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

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