import { Controller, Get, Post, Param, Query, Req, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { AffiliateService } from './affiliate.service';

@ApiTags('联盟返佣')
@Controller('affiliate')
export class AffiliateController {
  constructor(private affiliateService: AffiliateService) {}

  @Get('programs')
  getPrograms() {
    return this.affiliateService.getPrograms();
  }

  @Get('links')
  getLinks(@Query() query: { skillId?: string; toolId?: string; featured?: string }) {
    return this.affiliateService.getLinks({
      skillId: query.skillId,
      toolId: query.toolId ? Number(query.toolId) : undefined,
      featured: query.featured === 'true',
    });
  }

  @Get('stats')
  getStats() {
    return this.affiliateService.getStats();
  }

  @Get('user')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  getUserStats(@Query('userId') userId: string) {
    return this.affiliateService.getUserStats(userId);
  }

  @Post('click/:linkId')
  trackClick(@Param('linkId') linkId: string, @Query('userId') userId: string, @Req() req: any) {
    const ip = typeof req?.ip === 'string' ? req.ip : undefined;
    return this.affiliateService.trackClick(Number(linkId), userId, ip);
  }
}
