import {
    Controller,
    Put,
    Get,
    Body,
    Param,
    HttpStatus,
    NotFoundException,
    Delete,
    BadRequestException,
    Req,
    Post
} from '@nestjs/common'
import { HasAnyRoles, HasRoles } from '../auth/roles.decorator'
import { Role } from '../model/role.enum'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
import { PageRequest } from '../common/dto/page-request'
import { ApiUser } from './entities/api-user.entity'
import { ApiUserDto } from './dto/api-user.dto'
import { ApiUserService } from './api-user.service'
import { Public } from 'src/auth/public.decorator'

@ApiTags('apiUser')
@Controller('/apiUser')
@ApiBearerAuth()
export class ApiUserController {
    constructor(private readonly apiUserService: ApiUserService) {}

    @Post()
    public async list(@Body() page: PageRequest<ApiUser>, @Req() req) {
        return await this.apiUserService.findAll(page)
    }

    @Put()
    @HasRoles(Role.Admin)
    public async create(@Body() userId: number) {
        return await this.apiUserService.create(userId)
    }

    @Public()
    @Get('/get/:id')
    public async get(@Param('id') id: string, @Req() req) {
        const chatRole = await this.apiUserService.findById(Number(id))
        if (!req.user || req.user.id != chatRole.userId) {
            chatRole.code = ''
            chatRole.publicCode = ''
        }
        return chatRole
    }

    @Put('/:id')
    @HasAnyRoles(Role.Api, Role.Admin)
    public async update(@Param('id') id: string, @Body() apiUser: ApiUser) {
        try {
            await this.apiUserService.update(Number(id), apiUser)

            return {
                message: 'apiUser Updated successfully!',
                status: HttpStatus.OK
            }
        } catch (err) {
            throw new BadRequestException(err, 'Error: apiuser not updated!')
        }
    }

    @Delete('/:id')
    @HasRoles(Role.Admin)
    public async delete(@Param('id') id: number) {
        try {
            await this.apiUserService.delete(id)
            return {
                message: 'apiuser Deleted successfully!',
                status: HttpStatus.OK
            }
        } catch (err) {
            throw new BadRequestException(err, 'Error: apiuser not deleted!')
        }
    }
}
