import prisma from '../lib/prisma.js';

export interface CreateEmailLogData {
  fromAddress: string;
  toAddress: string;
  subject: string;
  context: string;
  customerId?: number;
  triggeredBy?: string;
  smtpServer: string;
  smtpPort: number;
  smtpEncryption: string;
  smtpUser: string;
  success: boolean;
  messageId?: string;
  errorMessage?: string;
  smtpResponse?: string;
}

export async function createEmailLog(data: CreateEmailLogData) {
  return prisma.emailLog.create({ data });
}

export async function getEmailLogs(options?: {
  page?: number;
  limit?: number;
  success?: boolean;
  search?: string;
  context?: string;
}) {
  const page = options?.page || 1;
  const limit = options?.limit || 50;
  const skip = (page - 1) * limit;

  const where: Record<string, unknown> = {};

  if (options?.success !== undefined) {
    where.success = options.success;
  }

  if (options?.context) {
    where.context = options.context;
  }

  if (options?.search) {
    where.OR = [
      { fromAddress: { contains: options.search } },
      { toAddress: { contains: options.search } },
      { subject: { contains: options.search } },
      { errorMessage: { contains: options.search } },
    ];
  }

  const [logs, total] = await Promise.all([
    prisma.emailLog.findMany({
      where,
      orderBy: { sentAt: 'desc' },
      skip,
      take: limit,
    }),
    prisma.emailLog.count({ where }),
  ]);

  return {
    data: logs,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit),
    },
  };
}

export async function getEmailLogById(id: number) {
  return prisma.emailLog.findUnique({ where: { id } });
}

export async function getEmailLogStats() {
  const [total, success, failed, last24h] = await Promise.all([
    prisma.emailLog.count(),
    prisma.emailLog.count({ where: { success: true } }),
    prisma.emailLog.count({ where: { success: false } }),
    prisma.emailLog.count({
      where: { sentAt: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } },
    }),
  ]);

  return { total, success, failed, last24h };
}
