import { getDb, queryOne, queryAll, execute } from '../db/database';
import type { Device } from '@network-tool/shared-types';

export class DeviceService {
  async registerDevice(userId: number, data: { device_name: string; device_fingerprint: string; public_key: string }): Promise<Device> {
    const db = await getDb();
    if (queryOne(db, 'SELECT id FROM devices WHERE device_fingerprint = ?', [data.device_fingerprint])) {
      throw new Error('DEVICE_ALREADY_EXISTS');
    }
    const result = execute(db,
      'INSERT INTO devices (user_id, device_name, device_fingerprint, public_key, status) VALUES (?, ?, ?, ?, ?)',
      [userId, data.device_name, data.device_fingerprint, data.public_key, 'offline']
    );
    return queryOne<Device>(db, 'SELECT * FROM devices WHERE id = ?', [result.lastInsertRowid])!;
  }

  async getUserDevices(userId: number): Promise<Device[]> {
    const db = await getDb();
    return queryAll<Device>(db, 'SELECT * FROM devices WHERE user_id = ? ORDER BY last_seen_at DESC', [userId]);
  }

  async getAllDevices(): Promise<Device[]> {
    const db = await getDb();
    return queryAll<Device>(db, 'SELECT * FROM devices ORDER BY last_seen_at DESC');
  }

  async updateDeviceStatus(deviceId: number, status: 'online' | 'offline'): Promise<Device | null> {
    const db = await getDb();
    const result = execute(db, "UPDATE devices SET status = ?, last_seen_at = datetime('now') WHERE id = ?", [status, deviceId]);
    if (result.changes === 0) return null;
    return queryOne<Device>(db, 'SELECT * FROM devices WHERE id = ?', [deviceId]);
  }

  async deleteDevice(deviceId: number, userId: number): Promise<boolean> {
    const db = await getDb();
    const result = execute(db, 'DELETE FROM devices WHERE id = ? AND user_id = ?', [deviceId, userId]);
    return result.changes > 0;
  }

  async adminDeleteDevice(deviceId: number): Promise<boolean> {
    const db = await getDb();
    const result = execute(db, 'DELETE FROM devices WHERE id = ?', [deviceId]);
    return result.changes > 0;
  }

  async getDeviceById(deviceId: number): Promise<Device | null> {
    const db = await getDb();
    return queryOne<Device>(db, 'SELECT * FROM devices WHERE id = ?', [deviceId]);
  }
}
