import { Controller, Get, Post, Body, Param, Query, HttpException, HttpStatus, UseGuards, Req, Res } from '@nestjs/common'
import { Request, Response } from 'express'
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'
import * as crypto from 'crypto'

@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)
  }

  // 泛匹配路由放在最后，避免拦截 stats/records/visitors 等
  @Public()
  @Get(':shareCode')
  async redirect(
    @Param('shareCode') shareCode: string,
    @Req() req: Request,
    @Res() res: Response,
  ) {
    try {
      const ip = req.ip || req.socket?.remoteAddress || 'unknown'
      const visitorId = crypto.createHash('md5').update(ip).digest('hex').slice(0, 16)
      let visitorUserId: string | undefined
      const token = req.query.token as string | undefined
      if (token) {
        try { const payload = this.jwtService.verify(token) as any; visitorUserId = payload.userId } catch {}
      }
      await this.shareService.visit(shareCode, visitorId, visitorUserId)
    } catch (e) {
      // 访问记录失败不影响跳转
    }
    res.redirect(HttpStatus.FOUND, `https://zhiyin.yzrcloud.cn/?share=${shareCode}`)
  }
}
