import { getDb } from '../database/database';

interface PushUser {
  id: number;
  account: string;
  notify_config: string;
  created_at: string;
  updated_at: string;
}

export function getAllPushUsers(): PushUser[] {
  const db = getDb();
  return db.prepare('SELECT * FROM push_users ORDER BY account ASC').all() as PushUser[];
}

export function getPushUserById(id: number): PushUser | undefined {
  const db = getDb();
  return db.prepare('SELECT * FROM push_users WHERE id = ?').get(id) as PushUser | undefined;
}

export function getPushUserByAccount(account: string): PushUser | undefined {
  const db = getDb();
  return db.prepare('SELECT * FROM push_users WHERE account = ?').get(account) as PushUser | undefined;
}

export function upsertPushUser(account: string, notifyConfig: string): PushUser | undefined {
  const db = getDb();
  const existing = getPushUserByAccount(account);
  if (existing) {
    db.prepare("UPDATE push_users SET notify_config = ?, updated_at = datetime('now', 'localtime') WHERE id = ?")
      .run(notifyConfig, existing.id);
    return getPushUserById(existing.id);
  } else {
    const result = db.prepare("INSERT INTO push_users (account, notify_config) VALUES (?, ?)")
      .run(account, notifyConfig);
    return getPushUserById(result.lastInsertRowid as number);
  }
}

export function updatePushUser(id: number, account: string, notifyConfig: string): PushUser | undefined {
  const db = getDb();
  db.prepare("UPDATE push_users SET account = ?, notify_config = ?, updated_at = datetime('now', 'localtime') WHERE id = ?")
    .run(account, notifyConfig, id);
  return getPushUserById(id);
}

export function deletePushUser(id: number): boolean {
  const db = getDb();
  const result = db.prepare('DELETE FROM push_users WHERE id = ?').run(id);
  return result.changes > 0;
}

export function findPushUserForConfig(configId: number): PushUser | undefined {
  if (!configId) return undefined;
  const db = getDb();
  const config = db.prepare('SELECT promotion_account FROM cloud_configs WHERE id = ?').get(configId) as any;
  if (!config || !config.promotion_account) return undefined;
  return getPushUserByAccount(config.promotion_account);
}
