/* eslint-disable @typescript-eslint/no-unsafe-argument */
import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
  Req,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth } from '@nestjs/swagger';
import { UsersService } from './users.service';
import { User } from '@schemas/user.schema';
import { Profile } from '@common/guards/profile.decorator';
import { JWToken } from '@dtos/general.interface';
import { FileInterceptor } from '@nestjs/platform-express';
import { Request } from 'express';
import { UserLogs } from '@schemas/user-logs.schema';

@ApiBearerAuth()
@Controller('users')
@UseGuards(AuthGuard('jwt'))
export class UsersController {
  constructor(private readonly userService: UsersService) {}

  @Get('profile')
  async findOne(@Profile() user: JWToken): Promise<User> {
    return await this.userService.findOne(user.userId);
  }

  @Get('all')
  async findAll(
    @Profile() user: JWToken,
    @Query('page') page: number = 1,
  ): Promise<User[]> {
    return await this.userService.findAll(user.userId, page);
  }

  @Get('logs')
  async findAllLogs(
    @Profile() user: JWToken,
    @Query('start') start: string,
    @Query('end') end: string,
    @Query('page') page: number = 1,
  ): Promise<UserLogs[]> {
    return await this.userService.findAllLogs(
      user.userId,
      start !== '' ? start : null,
      end !== '' ? end : null,
      page,
    );
  }

  @Put('updatetoken/:id')
  async updateToken(
    @Param('id') id: string,
    @Body() token: { token: string },
  ): Promise<User> {
    return await this.userService.updateToken(id, token);
  }

  @Post('logout')
  async logout(@Profile() user: JWToken, @Req() req: Request): Promise<void> {
    return await this.userService.logout(user.userId ?? '', req);
  }

  @Post('create')
  @UseInterceptors(FileInterceptor('new_photo'))
  async create(
    @UploadedFile() photo: Express.Multer.File,
    @Body() data: any,
    @Profile() user: JWToken,
  ): Promise<User> {
    return await this.userService.create(data, photo, user.userId);
  }

  @Post('update')
  @UseInterceptors(FileInterceptor('new_photo'))
  async update(
    @UploadedFile() photo: Express.Multer.File,
    @Body() data: any,
  ): Promise<User> {
    return await this.userService.update(data, photo);
  }

  @Delete('delete/:id')
  async remove(@Param('id') id: string): Promise<void> {
    return this.userService.remove(id);
  }
}
