// Auto-generated Logistic service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Logistic, CreateLogisticInput, UpdateLogisticInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateLogisticInput): Logistic {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = true;
    const cols = ["id", "order_id", "carrier", "tracking_number", "status", "events", "updated_at"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.orderId ?? null, input.carrier ?? null, input.trackingNumber ?? null, input.status ?? null, input.events ?? null, now];

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

  /** Update */
  update(id: string, input: UpdateLogisticInput): Logistic | undefined {
    const existing = this.getById(id);
    if (!existing) return undefined;

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.orderId !== undefined) { sets.push("order_id = ?"); values.push(input.orderId); }
    if (input.carrier !== undefined) { sets.push("carrier = ?"); values.push(input.carrier); }
    if (input.trackingNumber !== undefined) { sets.push("tracking_number = ?"); values.push(input.trackingNumber); }
    if (input.status !== undefined) { sets.push("status = ?"); values.push(input.status); }
    if (input.events !== undefined) { sets.push("events = ?"); values.push(input.events); }

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

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

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

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