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

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

  /**
   * 聚合联盟点击与预估收益（从 affiliate_clicks 实时计算，不再依赖手写统计表）
   */
  async getStats() {
    const grouped = await this.prisma.affiliateClick.groupBy({
      by: ['linkId'],
      _count: { _all: true },
    });

    const linkIds = grouped.map((g) => g.linkId);
    const links = linkIds.length
      ? await this.prisma.affiliateLink.findMany({ where: { id: { in: linkIds } } })
      : [];
    const linkMap = new Map(links.map((l) => [l.id, l]));

    let totalRevenue = 0;
    const ranked = grouped
      .map((g) => {
        const link = linkMap.get(g.linkId);
        const revenue = g._count._all * (link?.estimatedCommission ?? 0);
        totalRevenue += revenue;
        return {
          id: g.linkId,
          title: link?.title ?? '未知链接',
          clicks: g._count._all,
          estimatedRevenue: Number(revenue.toFixed(2)),
        };
      })
      .sort((a, b) => b.clicks - a.clicks);

    return {
      totalClicks: ranked.reduce((sum: number, r: { clicks: number }) => sum + r.clicks, 0),
      totalRevenue: Number(totalRevenue.toFixed(2)),
      topLinks: ranked.slice(0, 5),
    };
  }

  /**
   * 获取联盟计划（推广平台）列表
   */
  async getPrograms() {
    return this.prisma.affiliateProgram.findMany({
      where: { active: true },
      orderBy: { sortOrder: 'asc' },
    });
  }

  /**
   * 获取推广链接，可按技能/工具关联筛选
   */
  async getLinks(query: { skillId?: string; toolId?: number; featured?: boolean }) {
    const where: any = { active: true };
    if (query.skillId) where.skillId = query.skillId;
    if (query.toolId) where.toolId = query.toolId;
    if (query.featured) where.isFeatured = true;

    const links = await this.prisma.affiliateLink.findMany({
      where,
      include: { program: true },
      orderBy: [{ isFeatured: 'desc' }, { sortOrder: 'asc' }],
    });
    return { links };
  }

  /**
   * 记录一次联盟点击并返回跳转地址
   */
  async trackClick(linkId: number, userId?: string, ip?: string) {
    const link = await this.prisma.affiliateLink.findUnique({ where: { id: linkId } });
    if (!link || !link.active) {
      throw new NotFoundException('推广链接不存在');
    }

    await this.prisma.affiliateClick.create({
      data: {
        linkId,
        userId: userId ? Number(userId) : null,
        ip: ip ?? null,
      },
    });

    return { success: true, redirectUrl: link.url };
  }

  /**
   * 获取用户的联盟数据（邀请码等）
   */
  async getUserStats(userId: string) {
    const user = await this.prisma.user.findUnique({ where: { id: Number(userId) } });
    if (!user) throw new NotFoundException('用户不存在');

    return {
      referralCode: user.username || `user_${userId}`,
      totalClicks: 0,
      totalRevenue: 0,
      pendingRevenue: 0,
    };
  }
}
