import { getDb } from "../utils/db";

export interface User {
  telegram_id: number;
  username?: string;
  first_name: string;
  last_name?: string;
  is_subscribed: number;
  joined_at: string;
  last_active: string;
}

export const UserModel = {
  upsert(data: {
    telegramId: number;
    username?: string;
    firstName: string;
    lastName?: string;
  }) {
    const db = getDb();
    db.prepare(`
      INSERT INTO users (telegram_id, username, first_name, last_name, last_active)
      VALUES (@telegramId, @username, @firstName, @lastName, datetime('now'))
      ON CONFLICT(telegram_id) DO UPDATE SET
        username    = excluded.username,
        first_name  = excluded.first_name,
        last_name   = excluded.last_name,
        last_active = datetime('now')
    `).run(data);
  },

  countAll(): number {
    const db = getDb();
    const row = db.prepare("SELECT COUNT(*) as n FROM users").get() as { n: number };
    return row.n;
  },

  countSubscribed(): number {
    const db = getDb();
    const row = db
      .prepare("SELECT COUNT(*) as n FROM users WHERE is_subscribed = 1")
      .get() as { n: number };
    return row.n;
  },

  countToday(): number {
    const db = getDb();
    const row = db
      .prepare("SELECT COUNT(*) as n FROM users WHERE date(joined_at) = date('now')")
      .get() as { n: number };
    return row.n;
  },

  getAllSubscribed(): User[] {
    const db = getDb();
    return db
      .prepare("SELECT * FROM users WHERE is_subscribed = 1")
      .all() as User[];
  },
};
