import { prisma } from '../../../config/database';
import { termuxClient } from '../../../services/termux.client';
import { smsResponseSyncService } from '../../../services/sms-response-sync.service';

export const smsDeviceService = {
  /**
   * Get the latest device status from the database
   */
  async getStatus() {
    const latest = await prisma.smsDeviceStatus.findFirst({
      orderBy: { lastCheckedAt: 'desc' },
    });

    return latest || {
      isConnected: false,
      connectionType: null,
      batteryLevel: null,
      batteryStatus: null,
      totalSent: 0,
      lastCheckedAt: null,
    };
  },

  /**
   * Get device status history (last N entries)
   */
  async getHistory(limit = 50) {
    return prisma.smsDeviceStatus.findMany({
      orderBy: { lastCheckedAt: 'desc' },
      take: limit,
    });
  },

  /**
   * Get live device info directly from Termux
   */
  async getLiveInfo() {
    const [isAvailable, health, battery, deviceInfo] = await Promise.all([
      termuxClient.isAvailable(),
      termuxClient.getHealth(),
      termuxClient.getBattery(),
      termuxClient.getDeviceInfo(),
    ]);

    return { isAvailable, health, battery, deviceInfo };
  },

  /**
   * Trigger an immediate response sync
   */
  async triggerSync() {
    await smsResponseSyncService.sync();
    return { success: true };
  },
};
