// Auto-generated Order service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Order, CreateOrderInput, UpdateOrderInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateOrderInput): Order {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "status", "total_amount", "address_id", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.status ?? null, input.totalAmount ?? null, input.addressId ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateOrderInput): Order | 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.status !== undefined) { sets.push("status = ?"); values.push(input.status); }
    if (input.totalAmount !== undefined) { sets.push("total_amount = ?"); values.push(input.totalAmount); }
    if (input.addressId !== undefined) { sets.push("address_id = ?"); values.push(input.addressId); }

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

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

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

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