import { prisma } from '../../../config/database';
import { termuxClient } from '../../../services/termux.client';

export const smsMessagesService = {
  /**
   * Send a single ad-hoc SMS (not part of a campaign)
   */
  async sendSingle(phone: string, message: string) {
    const result = await termuxClient.sendSms(phone, message);

    const smsMessage = await prisma.smsMessage.create({
      data: {
        phone,
        message,
        direction: 'OUTBOUND',
        status: result.success ? 'SENT' : 'FAILED',
        connectionType: 'termux',
        sentAt: new Date(),
      },
    });

    return { ...smsMessage, termuxResult: result };
  },

  /**
   * Get recent messages (paginated, for overview)
   */
  async findAll(options: { page?: number; limit?: number; direction?: string; phone?: string } = {}) {
    const { page = 1, limit = 50, direction, phone } = options;
    const skip = (page - 1) * limit;

    const where: Record<string, unknown> = {};
    if (direction) where.direction = direction;
    if (phone) where.phone = { contains: phone };

    const [items, total] = await Promise.all([
      prisma.smsMessage.findMany({
        where,
        orderBy: { sentAt: 'desc' },
        skip,
        take: limit,
        include: {
          campaign: { select: { id: true, name: true } },
          conversation: { select: { id: true, contactName: true } },
        },
      }),
      prisma.smsMessage.count({ where }),
    ]);

    return { items, total, page, limit };
  },

  /**
   * Get messages that need follow-up (inbound, unread, no reply)
   */
  async getFollowups(limit = 50) {
    return prisma.smsMessage.findMany({
      where: {
        direction: 'INBOUND',
        isRead: false,
        responseType: { in: ['QUESTION', 'POSITIVE'] },
      },
      orderBy: { sentAt: 'desc' },
      take: limit,
      include: {
        conversation: { select: { id: true, contactName: true, phone: true } },
      },
    });
  },
};
