// 飞书 IM 适配器
import type { IMAdapter, IMSendOptions, IMMessageHandler, IMMessage } from '../types';
import { createLogger } from '../../utils/logger';
import { generateId } from '../../utils/id';

const log = createLogger('FeishuAdapter');

export class FeishuAdapter implements IMAdapter {
  name = 'feishu';
  private appId: string;
  private appSecret: string;
  private connected = false;
  private accessToken = '';
  private handlers: IMMessageHandler[] = [];
  private pollingInterval?: ReturnType<typeof setInterval>;

  constructor(appId: string, appSecret: string) {
    this.appId = appId;
    this.appSecret = appSecret;
  }

  async connect(): Promise<void> {
    if (!this.appId || !this.appSecret) {
      log.warn('Feishu credentials not configured, running in mock mode');
      this.connected = true;
      return;
    }

    try {
      // 获取 tenant_access_token
      const response = await fetch('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          app_id: this.appId,
          app_secret: this.appSecret,
        }),
      });

      const data: any = await response.json();
      if (data.code === 0) {
        this.accessToken = data.tenant_access_token;
        this.connected = true;
        log.info('Feishu connected successfully');
      } else {
        throw new Error(`Feishu auth failed: ${data.msg}`);
      }
    } catch (error: any) {
      log.error(`Feishu connection failed: ${error.message}`);
      // 降级到 mock 模式
      this.connected = true;
      log.warn('Running in mock mode');
    }
  }

  async disconnect(): Promise<void> {
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
    }
    this.connected = false;
    this.accessToken = '';
    log.info('Feishu disconnected');
  }

  async send(options: IMSendOptions): Promise<void> {
    if (!this.accessToken) {
      log.warn(`[Mock] Send to ${options.channelId}: ${options.content.slice(0, 100)}`);
      return;
    }

    const msgType = options.contentType === 'card' ? 'interactive' : 'text';
    const content = msgType === 'text'
      ? JSON.stringify({ text: options.content })
      : options.content;

    try {
      const response = await fetch('https://open.feishu.cn/open-apis/im/v1/messages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.accessToken}`,
        },
        body: JSON.stringify({
          receive_id: options.channelId,
          msg_type: msgType,
          content,
        }),
      });

      const data: any = await response.json();
      if (data.code !== 0) {
        log.error(`Feishu send failed: ${data.msg}`);
      }
    } catch (error: any) {
      log.error(`Feishu send error: ${error.message}`);
    }
  }

  onMessage(handler: IMMessageHandler): void {
    this.handlers.push(handler);
  }

  isConnected(): boolean {
    return this.connected;
  }

  // 模拟接收消息（用于本地测试）
  async simulateMessage(content: string, userId: string = 'test_user'): Promise<void> {
    const message: IMMessage = {
      id: generateId('msg'),
      channelType: 'feishu',
      channelId: 'test_channel',
      userId,
      userName: '测试用户',
      content,
      contentType: 'text',
      timestamp: new Date(),
    };

    for (const handler of this.handlers) {
      await handler(message);
    }
  }
}
