import { Controller, Get, Post, Body, Param, Query, HttpException, HttpStatus, UseGuards } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { ShareService } from './share.service'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
import { Public } from '../../common/decorators/public.decorator'

@Controller('share')
export class ShareController {
  constructor(
    private shareService: ShareService,
    private jwtService: JwtService,
  ) {}

  @UseGuards(JwtAuthGuard)
  @Post('create')
  async create(
    @CurrentUser('userId') userId: string,
    @Body() body: { type: string; refId?: string; title?: string; description?: string },
  ) {
    return this.shareService.create(userId, body)
  }

  @Public()
  @Get('visit/:shareCode')
  async visit(
    @Param('shareCode') shareCode: string,
    @Query('visitorId') visitorId?: string,
    @Query('token') token?: string,
  ) {
    if (!visitorId) {
      throw new HttpException('缺少访问者标识', HttpStatus.BAD_REQUEST)
    }
    let visitorUserId: string | undefined
    if (token) {
      try {
        const payload = this.jwtService.verify(token) as any
        visitorUserId = payload.userId
      } catch {}
    }
    return this.shareService.visit(shareCode, visitorId, visitorUserId)
  }

  @UseGuards(JwtAuthGuard)
  @Get('stats')
  async stats(@CurrentUser('userId') userId: string) {
    return this.shareService.stats(userId)
  }

  @UseGuards(JwtAuthGuard)
  @Get('records')
  async records(
    @CurrentUser('userId') userId: string,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.shareService.records(userId, Number(page) || 1, Number(pageSize) || 20)
  }

  @UseGuards(JwtAuthGuard)
  @Get('visitors')
  async visitors(
    @CurrentUser('userId') userId: string,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.shareService.visitors(userId, Number(page) || 1, Number(pageSize) || 20)
  }
}
