import { Controller, Get, Post, Req, Res, Sse, HttpCode, Query } from '@nestjs/common'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
import { ChatService } from './chat.service'
import { Observable } from 'rxjs'
import { Public } from '../auth/public.decorator'
import { HasRoles } from '../auth/roles.decorator'
import { Role } from '../model/role.enum'
import { format } from 'date-fns'

@ApiTags('chat')
@Controller('chat')
@ApiBearerAuth()
export class ChatController {
    constructor(private readonly chatService: ChatService) {}

    @Post('chat-process')
    @Sse()
    public chat(@Req() req, @Res() res): Observable<any> {
        return this.chatService.chat(req, res)
    }

    @Post('chat-process1')
    @Sse()
    public async chat1(@Req() req, @Res() res) {
        await this.chatService.chat1(req, res)
    }

    @Public()
    @Post('session')
    public async session(): Promise<any> {
        return { status: 'Success', message: '', data: { auth: true, model: 'gpt-3.5-turbo' } }
    }

    @Post('verify')
    public verify() {
        return { status: 'Success', message: 'Verify successfully', data: null }
    }

    @Get('/usage')
    public async getTokenUsage(@Req() req) {
        return this.chatService.getUsage(req.user.id)
    }

    @Post('/proxy')
    @HasRoles(Role.Api)
    public chatProxy(@Req() req) {
        return this.chatService.chatProxy(req)
    }

    @Post('/proxy/stream')
    @HasRoles(Role.Api)
    @Sse()
    public chatProxyStream(@Req() req) {
        return this.chatService.streamChatProxy(req)
    }

    @Get('/getDatas')
    public async getDatas(@Query() { apiUserId }) {
        const apiNum = await this.chatService.getCount(apiUserId?Number(apiUserId):undefined, Role.Api)
        const userNum = await this.chatService.getCount(apiUserId?Number(apiUserId):undefined, Role.User)
        const todayNum = await this.chatService.getCount(apiUserId?Number(apiUserId):undefined, undefined, format(new Date(), 'yyyy-MM-dd'))
        const week = await this.chatService.getWeekCount(apiUserId?Number(apiUserId):undefined)
        return {
            api: apiNum,
            user: userNum,
            today: todayNum,
            week: week
        }
    }
}
