// Auto-generated User service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { User, CreateUserInput, UpdateUserInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateUserInput): User {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = true;
    const hasUpdatedAt = true;
    const cols = ["id", "phone", "nickname", "avatar_url", "created_at", "updated_at"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.phone ?? null, input.nickname ?? null, input.avatarUrl ?? null, now, now];

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

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

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.phone !== undefined) { sets.push("phone = ?"); values.push(input.phone); }
    if (input.nickname !== undefined) { sets.push("nickname = ?"); values.push(input.nickname); }
    if (input.avatarUrl !== undefined) { sets.push("avatar_url = ?"); values.push(input.avatarUrl); }

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

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

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

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