import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
  ChannelAdapterPort,
  SendMessageParams,
  DeliveryResult,
} from '../../domain/ports/outbound/channel-adapter.port';
import { ChannelType } from '../../domain/value-objects/channel-type.vo';
import { randomUUID } from 'crypto';
import * as nodemailer from 'nodemailer';

@Injectable()
export class EmailAdapter implements ChannelAdapterPort {
  private readonly logger = new Logger(EmailAdapter.name);
  readonly channelType = ChannelType.EMAIL;

  constructor(private readonly config: ConfigService) {}

  async send(params: SendMessageParams): Promise<DeliveryResult> {
    try {
      const transporter = nodemailer.createTransport({
        host: this.config.get<string>('SMTP_HOST'),
        port: this.config.get<number>('SMTP_PORT', 587),
        secure: this.config.get<boolean>('SMTP_SECURE', false),
        auth: {
          user: this.config.get<string>('SMTP_USER'),
          pass: this.config.get<string>('SMTP_PASS'),
        },
      });

      const info = await transporter.sendMail({
        from: this.config.get<string>('SMTP_FROM', this.config.get<string>('SMTP_USER')!),
        to: params.to.email!,
        subject: `IT0 Notification [${params.priority}]`,
        text: params.content,
      });

      return { messageId: info.messageId ?? randomUUID(), status: 'sent' };
    } catch (error) {
      this.logger.error('Email send failed', error);
      return {
        messageId: randomUUID(),
        status: 'failed',
        error: error instanceof Error ? error.message : 'Email send failed',
      };
    }
  }

  async isAvailable(): Promise<boolean> {
    return !!this.config.get('SMTP_HOST');
  }
}
