/**
 * Billing Emails Service
 *
 * Handles sending billing emails to users and tracking email history.
 * Integrates with email service for billing communications.
 *
 * @module services/billing-emails
 */

import { prisma } from '@/lib/db';
import { billingEmailsAdapter } from '@/lib/adapters/billing';
import { sendEmail } from '@/lib/email';
import type {
  BillingEmail,
  SendBillingEmailRequest,
} from '@/lib/types/user-management.types';
import { QUERY_LIMITS } from '@/lib/constants/user-management.constants';

/**
 * Billing Emails Service Class
 *
 * Manages billing email communications with users
 */
export class BillingEmailsService {
  /**
   * Send a billing email to a user
   *
   * @param userId - User ID to send email to
   * @param staffId - Staff member sending the email
   * @param emailData - Email content and metadata
   * @returns Created billing email record
   *
   * @example
   * const email = await service.sendBillingEmail('user-123', 'staff-456', {
   *   subject: 'Invoice for December 2025',
   *   content: 'Your monthly invoice is attached',
   *   amount: 99.99,
   *   dueDate: '2025-12-31T00:00:00Z'
   * });
   */
  async sendBillingEmail(
    userId: string,
    staffId: string,
    emailData: SendBillingEmailRequest,
    ipAddress: string
  ): Promise<BillingEmail> {
    const { subject, content, amount, dueDate } = emailData;

    // Get user information
    const user = await this.getUserForBilling(userId);
    if (!user) {
      throw new Error('User not found');
    }

    // Create billing email record in Prisma
    const billingEmail = await billingEmailsAdapter.create({
      data: {
        userId,
        staffId,
        subject,
        body: content,
        amount: amount ? parseFloat(String(amount)) : null,
        dueDate: dueDate ? new Date(dueDate) : null,
        status: 'SENT',
      },
    });

    // Send actual email
    const emailHTML = this.generateBillingEmailHTML({
      userName: user.name || user.email,
      subject,
      content,
      amount,
      dueDate,
    });

    await sendEmail({
      to: user.email,
      subject,
      html: emailHTML,
    });

    // Create audit log

    console.log(`💰 Billing email sent to ${user.email} by staff ${staffId}`);

    return billingEmail;
  }

  /**
   * Get billing email history for a user
   *
   * @param userId - User ID
   * @param limit - Maximum number of emails to return
   * @returns Array of billing emails
   */
  async getEmailHistoryByUser(
    userId: string,
    limit: number = QUERY_LIMITS.BILLING_EMAILS
  ): Promise<BillingEmail[]> {
    const emails = await billingEmailsAdapter.findMany({
      where: { userId },
      orderBy: { sentAt: 'desc' },
      take: limit,
    });

    return emails;
  }

  /**
   * Get billing statistics for a user
   *
   * @param userId - User ID
   * @returns Billing statistics
   */
  async getBillingStats(userId: string) {
    const emails = await billingEmailsAdapter.findMany({
      where: { userId },
      select: { status: true, amount: true },
    });

    return {
      total: emails.length,
      sent: emails.filter((e) => e.status === 'SENT').length,
      opened: emails.filter((e) => e.status === 'OPENED').length,
      paid: emails.filter((e) => e.status === 'PAID').length,
      overdue: emails.filter((e) => e.status === 'OVERDUE').length,
      totalAmount: emails
        .reduce((sum, e) => sum + parseFloat(e.amount?.toString() || '0'), 0)
        .toFixed(2),
    };
  }

  // ============================================
  // PRIVATE HELPER METHODS
  // ============================================

  /**
   * Get user info for billing
   * @private
   */
  private async getUserForBilling(userId: string) {
    return await prisma.users.findUnique({
      where: { id: userId },
      select: {
        id: true,
        email: true,
        name: true,
        companyName: true,
      },
    });
  }

  /**
   * Generate HTML template for billing email
   * @private
   */
  private generateBillingEmailHTML(data: {
    userName: string;
    subject: string;
    content: string;
    amount?: number;
    dueDate?: string;
  }): string {
    const { userName, subject, content, amount, dueDate } = data;

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>${subject}</title>
        <style>
          body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
          }
          .container {
            max-width: 600px;
            margin: 40px auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          }
          .header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 30px;
            text-align: center;
          }
          .header h1 {
            margin: 0;
            font-size: 24px;
            font-weight: 600;
          }
          .content {
            padding: 30px;
          }
          .content p {
            margin: 0 0 15px 0;
          }
          .amount-box {
            background: #f0fdf4;
            border-left: 4px solid #10b981;
            padding: 20px;
            margin: 20px 0;
            border-radius: 4px;
          }
          .amount {
            font-size: 32px;
            font-weight: bold;
            color: #10b981;
            margin: 0;
          }
          .due-date {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 15px;
            margin: 20px 0;
            border-radius: 4px;
          }
          .footer {
            background: #f9fafb;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #6b7280;
            border-top: 1px solid #e5e7eb;
          }
          .button {
            display: inline-block;
            padding: 12px 24px;
            background: #10b981;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 500;
            margin: 20px 0;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Mawidi Billing Notice</h1>
          </div>

          <div class="content">
            <p>Dear ${userName},</p>

            <div style="white-space: pre-wrap; margin: 20px 0;">${content}</div>

            ${
              amount
                ? `
              <div class="amount-box">
                <p style="margin: 0 0 5px 0; font-size: 14px; color: #6b7280;">Amount Due</p>
                <p class="amount">$${parseFloat(String(amount)).toFixed(2)}</p>
              </div>
            `
                : ''
            }

            ${
              dueDate
                ? `
              <div class="due-date">
                <strong>⏰ Payment Due:</strong>
                ${new Date(dueDate).toLocaleDateString('en-US', {
                  weekday: 'long',
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                })}
              </div>
            `
                : ''
            }

            <p style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
              If you have any questions about this invoice, please don't hesitate to contact our support team.
            </p>

            <p style="color: #6b7280; font-size: 14px;">
              Best regards,<br>
              The Mawidi Team
            </p>
          </div>

          <div class="footer">
            <p>This is an automated billing notification from Mawidi.</p>
            <p>© ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
            <p style="margin-top: 10px;">
              <a href="mailto:support@mawidi.com" style="color: #10b981;">support@mawidi.com</a>
            </p>
          </div>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Send seat purchase confirmation email
   *
   * @param params - Seat purchase details
   * @returns Promise<void>
   */
  async sendSeatPurchaseConfirmation(params: {
    userEmail: string;
    userName: string;
    quantity: number;
    pricePerSeat: number;
    totalAmount: number;
    currency: string;
    newTotalSeats: number;
  }): Promise<void> {
    const { userEmail, userName, quantity, pricePerSeat, totalAmount, currency, newTotalSeats } = params;

    const currencySymbol = this.getCurrencySymbol(currency);
    const subject = `Seat Purchase Confirmation - ${quantity} seat${quantity > 1 ? 's' : ''} added`;

    const emailHTML = this.generateSeatPurchaseEmailHTML({
      userName,
      quantity,
      pricePerSeat,
      totalAmount,
      currencySymbol,
      newTotalSeats,
    });

    await sendEmail({
      to: userEmail,
      subject,
      html: emailHTML,
    });

    console.log(`🪑 Seat purchase confirmation sent to ${userEmail} for ${quantity} seats`);
  }

  /**
   * Get currency symbol
   * @private
   */
  private getCurrencySymbol(currency: string): string {
    const symbols: Record<string, string> = {
      gbp: '£',
      usd: '$',
      eur: '€',
      qar: 'QAR ',
      aed: 'AED ',
      sar: 'SAR ',
    };
    return symbols[currency.toLowerCase()] || currency.toUpperCase() + ' ';
  }

  /**
   * Generate HTML template for seat purchase confirmation
   * @private
   */
  private generateSeatPurchaseEmailHTML(data: {
    userName: string;
    quantity: number;
    pricePerSeat: number;
    totalAmount: number;
    currencySymbol: string;
    newTotalSeats: number;
  }): string {
    const { userName, quantity, pricePerSeat, totalAmount, currencySymbol, newTotalSeats } = data;

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Seat Purchase Confirmation</title>
        <style>
          body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
          }
          .container {
            max-width: 600px;
            margin: 40px auto;
            background: #ffffff;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
          }
          .header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 40px 30px;
            text-align: center;
          }
          .header-icon {
            font-size: 48px;
            margin-bottom: 15px;
          }
          .header h1 {
            margin: 0;
            font-size: 24px;
            font-weight: 600;
          }
          .header p {
            margin: 10px 0 0 0;
            opacity: 0.9;
            font-size: 16px;
          }
          .content {
            padding: 30px;
          }
          .purchase-details {
            background: #f0fdf4;
            border-radius: 8px;
            padding: 24px;
            margin: 20px 0;
          }
          .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #d1fae5;
          }
          .detail-row:last-child {
            border-bottom: none;
            padding-top: 15px;
            margin-top: 5px;
            border-top: 2px solid #10b981;
          }
          .detail-label {
            color: #6b7280;
            font-size: 14px;
          }
          .detail-value {
            font-weight: 600;
            color: #1f2937;
          }
          .total-value {
            font-size: 20px;
            color: #10b981;
          }
          .info-box {
            background: #eff6ff;
            border-left: 4px solid #3b82f6;
            padding: 16px;
            margin: 20px 0;
            border-radius: 0 8px 8px 0;
          }
          .info-box p {
            margin: 0;
            color: #1e40af;
            font-size: 14px;
          }
          .footer {
            background: #f9fafb;
            padding: 24px;
            text-align: center;
            font-size: 12px;
            color: #6b7280;
            border-top: 1px solid #e5e7eb;
          }
          .button {
            display: inline-block;
            padding: 14px 28px;
            background: #10b981;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 600;
            margin: 20px 0;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <div class="header-icon">🪑</div>
            <h1>Seats Added Successfully!</h1>
            <p>Your team just got bigger</p>
          </div>

          <div class="content">
            <p>Hi ${userName},</p>

            <p>Great news! Your seat purchase has been processed successfully. Here are the details:</p>

            <div class="purchase-details">
              <div class="detail-row">
                <span class="detail-label">Seats Purchased</span>
                <span class="detail-value">${quantity} seat${quantity > 1 ? 's' : ''}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">Price per Seat</span>
                <span class="detail-value">${currencySymbol}${pricePerSeat.toFixed(2)}/month</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">Total Seats Now</span>
                <span class="detail-value">${newTotalSeats} seats</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">Amount Charged</span>
                <span class="detail-value total-value">${currencySymbol}${totalAmount.toFixed(2)}</span>
              </div>
            </div>

            <div class="info-box">
              <p><strong>💡 What's next?</strong> You can now invite ${quantity} more team member${quantity > 1 ? 's' : ''} from your Team Management dashboard.</p>
            </div>

            <p style="text-align: center;">
              <a href="${process.env.NEXT_PUBLIC_APP_URL || 'https://app.mawidi.com'}/en/dashboard?tab=team" class="button">
                Go to Team Management
              </a>
            </p>

            <p style="color: #6b7280; font-size: 14px; margin-top: 30px;">
              Thank you for growing your team with Mawidi!<br><br>
              Best regards,<br>
              The Mawidi Team
            </p>
          </div>

          <div class="footer">
            <p>This is an automated confirmation from Mawidi.</p>
            <p>© ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
            <p style="margin-top: 10px;">
              <a href="mailto:support@mawidi.com" style="color: #10b981;">support@mawidi.com</a>
            </p>
          </div>
        </div>
      </body>
      </html>
    `;
  }
}

// Export singleton instance
export const billingEmailsService = new BillingEmailsService();
