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';

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

  constructor(private readonly config: ConfigService) {}

  async send(params: SendMessageParams): Promise<DeliveryResult> {
    const webhookUrl = this.config.get<string>('WECHAT_WORK_WEBHOOK_URL');

    try {
      const response = await fetch(webhookUrl!, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          msgtype: 'text',
          text: {
            content: params.content,
            mentioned_list: [params.to.wechatId],
          },
        }),
      });

      if (!response.ok) {
        const errorData = await response.text();
        throw new Error(`WeChat Work API error: ${response.status} ${errorData}`);
      }

      const data = await response.json();
      if (data.errcode !== 0) {
        throw new Error(`WeChat Work error: ${data.errmsg}`);
      }

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

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