import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { PrismaService } from '@common/prisma/prisma.service';
import { RedisService } from '@common/redis/redis.service';
import { MarketService } from '../market/market.service';

export interface PriceAlert {
  id: string;
  symbol: string;
  alertType: 'above' | 'below';
  alertPrice: number;
  isActive: boolean;
}

@Injectable()
export class AlertService {
  private readonly logger = new Logger(AlertService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly redis: RedisService,
    private readonly marketService: MarketService,
  ) {}

  /**
   * 创建价格预警
   */
  async createAlert(
    userId: number,
    symbol: string,
    alertType: 'above' | 'below',
    alertPrice: number,
  ): Promise<PriceAlert> {
    // 验证品种存在
    await this.marketService.getProduct(symbol);

    const alert = await this.prisma.priceAlert.create({
      data: {
        userId,
        symbol: symbol.toUpperCase(),
        alertType,
        alertPrice,
        isActive: true,
      },
    });

    return {
      id: alert.id.toString(),
      symbol: alert.symbol,
      alertType: alert.alertType as 'above' | 'below',
      alertPrice: Number(alert.alertPrice),
      isActive: alert.isActive,
    };
  }

  /**
   * 获取用户的价格预警
   */
  async getUserAlerts(userId: number): Promise<PriceAlert[]> {
    const alerts = await this.prisma.priceAlert.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
    });

    return alerts.map((alert) => ({
      id: alert.id.toString(),
      symbol: alert.symbol,
      alertType: alert.alertType as 'above' | 'below',
      alertPrice: Number(alert.alertPrice),
      isActive: alert.isActive,
    }));
  }

  /**
   * 删除价格预警
   */
  async deleteAlert(userId: number, alertId: string): Promise<void> {
    const alert = await this.prisma.priceAlert.findFirst({
      where: {
        id: parseInt(alertId),
        userId,
      },
    });

    if (!alert) {
      throw new Error('预警不存在');
    }

    await this.prisma.priceAlert.delete({
      where: { id: parseInt(alertId) },
    });
  }

  /**
   * 停用/启用预警
   */
  async toggleAlert(userId: number, alertId: string, isActive: boolean): Promise<PriceAlert> {
    const alert = await this.prisma.priceAlert.update({
      where: {
        id: parseInt(alertId),
      },
      data: { isActive },
    });

    return {
      id: alert.id.toString(),
      symbol: alert.symbol,
      alertType: alert.alertType as 'above' | 'below',
      alertPrice: Number(alert.alertPrice),
      isActive: alert.isActive,
    };
  }

  /**
   * 定时检查价格预警
   */
  @Cron(CronExpression.EVERY_MINUTE)
  async checkPriceAlerts() {
    try {
      const activeAlerts = await this.prisma.priceAlert.findMany({
        where: { isActive: true },
      });

      for (const alert of activeAlerts) {
        try {
          const tick = await this.marketService.getTickData(alert.symbol);
          const currentPrice = tick.price;
          const alertPrice = Number(alert.alertPrice);

          let triggered = false;

          if (alert.alertType === 'above' && currentPrice >= alertPrice) {
            triggered = true;
          } else if (alert.alertType === 'below' && currentPrice <= alertPrice) {
            triggered = true;
          }

          if (triggered) {
            // 标记为已触发
            await this.prisma.priceAlert.update({
              where: { id: alert.id },
              data: {
                isActive: false,
                triggeredAt: new Date(),
              },
            });

            // TODO: 发送通知（邮件/短信/推送）
            this.logger.log(
              `价格预警触发: ${alert.symbol} ${alert.alertType} ${alertPrice}, 当前价格: ${currentPrice}`,
            );
          }
        } catch (error) {
          this.logger.error(`检查预警失败 ${alert.symbol}:`, error.message);
        }
      }
    } catch (error) {
      this.logger.error('检查价格预警失败:', error.message);
    }
  }
}
