import { Controller, Get, UseGuards, Req, NotFoundException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { IssuerStatsService } from '../../../application/services/issuer-stats.service';
import { IssuerService } from '../../../application/services/issuer.service';

@ApiTags('Issuer Stats')
@Controller('issuers/me')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
export class IssuerStatsController {
  constructor(
    private readonly issuerStatsService: IssuerStatsService,
    private readonly issuerService: IssuerService,
  ) {}

  private async getIssuerId(userId: string): Promise<string> {
    const issuer = await this.issuerService.findByUserId(userId);
    if (!issuer) throw new NotFoundException('Issuer profile not found');
    return issuer.id;
  }

  @Get('stats')
  @ApiOperation({ summary: 'Get issuer dashboard stats' })
  async getStats(@Req() req: any) {
    const issuerId = await this.getIssuerId(req.user.id);
    const stats = await this.issuerStatsService.getDashboardStats(issuerId);
    return { code: 0, data: stats };
  }

  @Get('credit')
  @ApiOperation({ summary: 'Get issuer credit score details' })
  async getCreditDetails(@Req() req: any) {
    const issuerId = await this.getIssuerId(req.user.id);
    const credit = await this.issuerStatsService.getCreditDetails(issuerId);
    return { code: 0, data: credit };
  }

  @Get('coupons')
  @ApiOperation({ summary: 'Get issuer coupon list' })
  async getCoupons(@Req() req: any) {
    const issuerId = await this.getIssuerId(req.user.id);
    return { code: 0, data: { issuerId, items: [], total: 0 } };
  }

  @Get('analytics/users')
  @ApiOperation({ summary: 'Get issuer user analytics' })
  async getAnalyticsUsers(@Req() req: any) {
    return { code: 0, data: { totalUsers: 0, activeUsers: 0, newUsers: 0 } };
  }

  @Get('analytics/demographics')
  @ApiOperation({ summary: 'Get issuer user demographics' })
  async getAnalyticsDemographics(@Req() req: any) {
    return { code: 0, data: { ageGroups: [], genderDistribution: [] } };
  }

  @Get('analytics/repurchase')
  @ApiOperation({ summary: 'Get issuer repurchase rate analytics' })
  async getAnalyticsRepurchase(@Req() req: any) {
    return { code: 0, data: { repurchaseRate: 0, trend: [] } };
  }

  @Get('analytics/ai-insights')
  @ApiOperation({ summary: 'Get AI-powered issuer insights' })
  async getAnalyticsAiInsights(@Req() req: any) {
    return { code: 0, data: { insights: [] } };
  }
}
