import { Controller, Get, Req } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { EffectiveMembershipService } from './effective-membership.service';
import { PrismaService } from '../../infrastructure/database/prisma.service';

@ApiTags('membership')
@Controller('membership')
export class MembershipController {
  constructor(
    private readonly service: EffectiveMembershipService,
    private readonly prisma: PrismaService,
  ) {}

  /**
   * GET /membership/plans
   * 返回可用计划列表（含权益摘要）。不返回硬编码价格。
   */
  @Get('plans')
  @ApiOperation({ summary: '可用会员计划列表' })
  async getPlans() {
    const plans = await this.prisma.membershipPlan.findMany({
      where: { isActive: true },
      select: {
        code: true, name: true,
        maxKnowledgeBases: true, maxStorageBytes: true, maxFileSizeBytes: true,
        monthlyOcrPages: true, monthlyVisionPages: true, monthlyChatCount: true,
        monthlyAiAnalysisCount: true, monthlyRecallCount: true,
        monthlyCardGenCount: true, monthlyQuizCount: true,
        priceMonthly: true, priceYearly: true,
      },
      orderBy: { priceMonthly: 'asc' },
    });

    return {
      plans: plans.map(p => ({
        planCode: p.code,
        name: p.name,
        entitlements: {
          maxKnowledgeBases: p.maxKnowledgeBases,
          maxStorageBytes: Number(p.maxStorageBytes),
          maxFileSizeBytes: Number(p.maxFileSizeBytes),
          monthlyOcrPages: p.monthlyOcrPages,
          monthlyVisionPages: p.monthlyVisionPages,
          monthlyChatCount: p.monthlyChatCount,
          monthlyAiAnalysisCount: p.monthlyAiAnalysisCount,
          monthlyRecallCount: p.monthlyRecallCount,
          monthlyCardGenCount: p.monthlyCardGenCount,
          monthlyQuizCount: p.monthlyQuizCount,
        },
        priceMonthly: p.priceMonthly,
        priceYearly: p.priceYearly,
      })),
    };
  }

  /**
   * GET /membership/me
   * 返回当前用户有效会员、Grant 摘要、appAccountToken。
   * 不返回完整 transactionId/originalTransactionId。
   */
  @Get('me')
  @ApiOperation({ summary: '当前会员状态' })
  async getMyMembership(@Req() req: any) {
    const userId = req.user.id;
    const membership = await this.service.compute(userId);
    const entitlements = await this.service.getEntitlements(userId);

    return {
      effectivePlan: membership.effectivePlan,
      grants: membership.grants.map(g => ({
        source: g.source, status: g.status,
        planCode: g.planCode, planName: g.planName,
        startedAt: g.startedAt, expiresAt: g.expiresAt,
        autoRenewStatus: g.autoRenewStatus,
        environment: g.environment,
      })),
      appAccountToken: membership.appAccountToken,
      entitlements: entitlements.entitlements,
      usageSummary: {
        // 由 Issue 07-08 填充实际使用量
        used: null,
        remaining: null,
        nextRefresh: null,
      },
    };
  }

  /**
   * GET /membership/usage
   * 返回当前有效 Plan 的额度摘要。实际使用量由 Issue 07-08 填充。
   */
  @Get('usage')
  @ApiOperation({ summary: '当前额度使用情况' })
  async getUsage(@Req() req: any) {
    const entitlements = await this.service.getEntitlements(req.user.id);

    return {
      planCode: entitlements.planCode,
      quota: entitlements.entitlements,
      used: null,
      remaining: null,
      window: null,
      nextRefresh: null,
    };
  }
}
