import {
    Controller,
    Get,
    Body,
    Param,
    HttpStatus,
    NotFoundException,
    BadRequestException,
    Req,
    Post
} from '@nestjs/common'
import { UsersService } from './users.service'
import { UserProfileDto } from './dto/user-profile.dto'
import { IUsers } from './interfaces/users.interface'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
import { Users } from './entities/users.entity'

@ApiTags('users')
@Controller('users')
@ApiBearerAuth()
export class UsersController {
    constructor(private readonly usersService: UsersService) {}

    @Get('/my')
    public async my(@Req() req) {
        return await this.get(req)
    }

    @Get('/get')
    public async get(@Req() req): Promise<IUsers> {
        const user = await this.usersService.findById(req.user.userId)
        return user
    }

    @Post('/update')
    public async update(@Body() userProfileDto: UserProfileDto, @Req() req): Promise<any> {
        try {
            await this.usersService.updateProfileUser(req.user.userId, userProfileDto)

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

    @Post('/updatePassword')
    public async updatePassword(@Body() { password }, @Req() req) {
        await this.usersService.updatePassword(req.user.id, password)
    }

    @Get('/invites')
    public async invites(@Req() req) {
        return this.usersService.getInvites(req.user.id)
    }

    @Get('/:userId')
    public async findOneUser(@Param('userId') userId: string): Promise<IUsers> {
        return this.usersService.findById(Number(userId))
    }

    @Get('/:userId/profile')
    public async getUser(@Param('userId') userId: string): Promise<any> {
        const user = await this.findOneUser(userId)

        if (!user) {
            throw new NotFoundException('User does not exist!')
        }

        return {
            user: user,
            status: HttpStatus.OK
        }
    }
}
