import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { PrismaService } from '@common/prisma/prisma.service';
import { MarketService } from '../market/market.service';

export interface WatchlistItem {
  id: string;
  symbol: string;
  name: string;
  price: number;
  change: number;
  changePercent: number;
  alertPrice?: number;
  addTime: string;
}

@Injectable()
export class WatchlistService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly marketService: MarketService,
  ) {}

  async getWatchlist(userId: number): Promise<WatchlistItem[]> {
    const items = await this.prisma.watchlist.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
    });

    const result: WatchlistItem[] = [];

    for (const item of items) {
      try {
        const product = await this.marketService.getProduct(item.symbol);
        result.push({
          id: item.id.toString(),
          symbol: item.symbol,
          name: product.name,
          price: product.price,
          change: product.change,
          changePercent: product.changePercent,
          alertPrice: item.alertPrice ? Number(item.alertPrice) : undefined,
          addTime: item.createdAt.toISOString(),
        });
      } catch (error) {
        // 如果品种不存在，跳过
      }
    }

    return result;
  }

  async addToWatchlist(
    userId: number,
    symbol: string,
    alertPrice?: number,
  ): Promise<WatchlistItem> {
    // 检查品种是否存在
    const product = await this.marketService.getProduct(symbol);

    // 检查是否已存在
    const existing = await this.prisma.watchlist.findUnique({
      where: {
        userId_symbol: {
          userId,
          symbol: symbol.toUpperCase(),
        },
      },
    });

    if (existing) {
      throw new ConflictException('该品种已在自选股中');
    }

    const item = await this.prisma.watchlist.create({
      data: {
        userId,
        symbol: symbol.toUpperCase(),
        alertPrice: alertPrice || null,
      },
    });

    return {
      id: item.id.toString(),
      symbol: item.symbol,
      name: product.name,
      price: product.price,
      change: product.change,
      changePercent: product.changePercent,
      alertPrice: item.alertPrice ? Number(item.alertPrice) : undefined,
      addTime: item.createdAt.toISOString(),
    };
  }

  async removeFromWatchlist(userId: number, symbol: string): Promise<void> {
    const item = await this.prisma.watchlist.findUnique({
      where: {
        userId_symbol: {
          userId,
          symbol: symbol.toUpperCase(),
        },
      },
    });

    if (!item) {
      throw new NotFoundException('该品种不在自选股中');
    }

    await this.prisma.watchlist.delete({
      where: { id: item.id },
    });
  }

  async updateAlertPrice(
    userId: number,
    symbol: string,
    alertPrice: number,
  ): Promise<WatchlistItem> {
    const item = await this.prisma.watchlist.findUnique({
      where: {
        userId_symbol: {
          userId,
          symbol: symbol.toUpperCase(),
        },
      },
    });

    if (!item) {
      throw new NotFoundException('该品种不在自选股中');
    }

    const updated = await this.prisma.watchlist.update({
      where: { id: item.id },
      data: { alertPrice },
    });

    const product = await this.marketService.getProduct(symbol);

    return {
      id: updated.id.toString(),
      symbol: updated.symbol,
      name: product.name,
      price: product.price,
      change: product.change,
      changePercent: product.changePercent,
      alertPrice: updated.alertPrice ? Number(updated.alertPrice) : undefined,
      addTime: updated.createdAt.toISOString(),
    };
  }
}
