import { env } from '../config/env';
import { prisma } from '../config/database';
import { logger } from '../utils/logger';
import { termuxClient } from './termux.client';

class SmsDeviceMonitorService {
  private interval: ReturnType<typeof setInterval> | null = null;

  start() {
    if (this.interval) return;

    // Delay initial check by 15s to stagger with response sync (avoids concurrent Termux API calls)
    setTimeout(() => {
      this.check().catch((err) => {
        logger.warn('Initial SMS device check failed:', err instanceof Error ? err.message : err);
      });
    }, 15_000);

    this.interval = setInterval(() => {
      this.check().catch((err) => {
        logger.warn('SMS device check failed:', err instanceof Error ? err.message : err);
      });
    }, env.SMS_DEVICE_MONITOR_INTERVAL_MS);

    logger.info(`SMS device monitor started (interval: ${env.SMS_DEVICE_MONITOR_INTERVAL_MS}ms, initial delay: 15s)`);
  }

  stop() {
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
  }

  async check() {
    const [isAvailable, battery, health] = await Promise.all([
      termuxClient.isAvailable(),
      termuxClient.getBattery(),
      termuxClient.getHealth(),
    ]);

    await prisma.smsDeviceStatus.create({
      data: {
        isConnected: isAvailable,
        connectionType: isAvailable ? 'termux' : null,
        batteryLevel: battery?.percentage ?? null,
        batteryStatus: battery?.status ?? null,
        totalSent: health?.messages_sent ?? 0,
        lastCheckedAt: new Date(),
      },
    });

    // Prune old entries — keep last 100
    const count = await prisma.smsDeviceStatus.count();
    if (count > 100) {
      const oldest = await prisma.smsDeviceStatus.findMany({
        orderBy: { lastCheckedAt: 'asc' },
        take: count - 100,
        select: { id: true },
      });
      if (oldest.length > 0) {
        await prisma.smsDeviceStatus.deleteMany({
          where: { id: { in: oldest.map((r) => r.id) } },
        });
      }
    }
  }
}

export const smsDeviceMonitorService = new SmsDeviceMonitorService();
