import { Injectable } from '@nestjs/common';
import { PrismaService } from '@common/prisma/prisma.service';

export interface HotEvent {
  id: string;
  title: string;
  summary: string;
  content?: string;
  time: string;
  impact: 'bullish' | 'bearish' | 'neutral';
  impactLevel: number;
  affectedProducts: string[];
  analysis?: string;
  risks?: string[];
  source?: string;
}

@Injectable()
export class EventsService {
  constructor(private readonly prisma: PrismaService) {}

  async getEvents(
    impact?: string,
    startDate?: Date,
    endDate?: Date,
    page = 1,
    size = 20,
  ): Promise<{ list: HotEvent[]; total: number }> {
    const where: any = {};

    if (impact && impact !== 'all') {
      where.impact = impact;
    }

    if (startDate || endDate) {
      where.eventTime = {};
      if (startDate) where.eventTime.gte = startDate;
      if (endDate) where.eventTime.lte = endDate;
    }

    const [events, total] = await Promise.all([
      this.prisma.hotEvent.findMany({
        where,
        include: {
          affectedProducts: {
            include: {
              product: true,
            },
          },
        },
        orderBy: { eventTime: 'desc' },
        skip: (page - 1) * size,
        take: size,
      }),
      this.prisma.hotEvent.count({ where }),
    ]);

    const list = events.map((e) => ({
      id: e.id.toString(),
      title: e.title,
      summary: e.summary || '',
      content: e.content || undefined,
      time: e.eventTime?.toISOString() || e.createdAt.toISOString(),
      impact: e.impact as 'bullish' | 'bearish' | 'neutral',
      impactLevel: e.impactLevel,
      affectedProducts: e.affectedProducts.map((ep) => ep.product.symbol),
      analysis: e.analysis || undefined,
      risks: e.risks || undefined,
      source: e.source || undefined,
    }));

    return { list, total };
  }

  async getEventById(id: string): Promise<HotEvent | null> {
    const event = await this.prisma.hotEvent.findUnique({
      where: { id: parseInt(id) },
      include: {
        affectedProducts: {
          include: {
            product: true,
          },
        },
      },
    });

    if (!event) return null;

    return {
      id: event.id.toString(),
      title: event.title,
      summary: event.summary || '',
      content: event.content || undefined,
      time: event.eventTime?.toISOString() || event.createdAt.toISOString(),
      impact: event.impact as 'bullish' | 'bearish' | 'neutral',
      impactLevel: event.impactLevel,
      affectedProducts: event.affectedProducts.map((ep) => ep.product.symbol),
      analysis: event.analysis || undefined,
      risks: event.risks || undefined,
      source: event.source || undefined,
    };
  }

  // 创建示例事件数据（用于初始化）
  async seedEvents() {
    const events = [
      {
        title: '地缘政治风险升级',
        summary: '美以袭伊朗，"海上油阀"被关，中东局势紧张升级',
        content: '详细内容...',
        impact: 'bullish',
        impactLevel: 5,
        analysis: '地缘政治风险急剧升温，霍尔木兹海峡封锁风险上升。原油供应中断担忧推动油价上涨，避险资产黄金、白银同步走强。',
        risks: ['冲突升级可能', '供应中断风险', '波动率激增'],
        affectedSymbols: ['SC', 'AU', 'AG'],
      },
      {
        title: '黄金价格创历史新高',
        summary: 'COMEX黄金突破3100美元关口，避险需求强劲',
        content: '详细内容...',
        impact: 'bullish',
        impactLevel: 4,
        analysis: '特朗普关税政策引发市场担忧，叠加地缘政治风险，黄金避险属性凸显。技术面突破历史高点，多头趋势强劲。',
        risks: ['获利回吐压力', '美元反弹风险', '美联储政策转向'],
        affectedSymbols: ['AU', 'AG'],
      },
      {
        title: '铜供应紧张预期',
        summary: '全球铜市场预计出现18万吨供应缺口',
        content: '详细内容...',
        impact: 'bullish',
        impactLevel: 4,
        analysis: '铜精矿TC现货指数持续回落，矿山供应增长放缓。美国可能加征铜进口关税，刺激美铜价格上涨。',
        risks: ['需求放缓风险', '美元走强压制', '库存累积'],
        affectedSymbols: ['CU'],
      },
    ];

    for (const event of events) {
      const existing = await this.prisma.hotEvent.findFirst({
        where: { title: event.title },
      });

      if (!existing) {
        // 查找产品ID
        const products = await this.prisma.product.findMany({
          where: { symbol: { in: event.affectedSymbols } },
        });

        await this.prisma.hotEvent.create({
          data: {
            title: event.title,
            summary: event.summary,
            content: event.content,
            impact: event.impact,
            impactLevel: event.impactLevel,
            analysis: event.analysis,
            risks: event.risks,
            affectedProducts: {
              create: products.map((p) => ({
                productId: p.id,
                impactConfidence: 0.8,
              })),
            },
          },
        });
      }
    }
  }
}
