/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
import {
  Body,
  Controller,
  Delete,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Post,
  Put,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth } from '@nestjs/swagger';
import { BusinessService } from './business.service';
import { Business } from '@schemas/business.schema';
import { Roles } from '@common/guards/roles.decorator';
import { RolesGuard } from '@common/guards/roles.guard';
import { UsersService } from '@modules/users/users.service';
import { User } from '@schemas/user.schema';
import { FileInterceptor } from '@nestjs/platform-express';

@ApiBearerAuth()
@Controller('business')
@UseGuards(AuthGuard('jwt'))
export class BusinessController {
  constructor(
    private readonly businessService: BusinessService,
    private readonly userService: UsersService,
  ) {}

  // Admin users
  @Post('admins/new')
  @UseGuards(RolesGuard)
  @Roles('creator')
  @UseInterceptors(FileInterceptor('new_photo'))
  async createAdmin(
    @UploadedFile() photo: Express.Multer.File,
    @Body() data: any,
  ): Promise<User> {
    return await this.userService.create(data, photo, data.businessId, true);
  }

  @Post()
  @UseGuards(RolesGuard)
  @Roles('creator')
  async create(@Body() dto: any): Promise<Business> {
    return this.businessService.create(dto);
  }

  // Admin users
  @Get('admins')
  @UseGuards(RolesGuard)
  @Roles('creator')
  async findAllAdmins(): Promise<User[]> {
    const users = await this.userService.findAllAdmins();
    return users;
  }

  @Get(':id')
  @UseGuards(RolesGuard)
  @Roles('creator')
  async findOne(@Param('id') id: string): Promise<Business> {
    const business = await this.businessService.findOne(id);
    if (!business) {
      throw new HttpException('El negocio no existe', HttpStatus.NOT_FOUND);
    }
    return business;
  }

  @Get()
  @UseGuards(RolesGuard)
  @Roles('creator')
  async findAll(): Promise<Business[]> {
    const businesses = await this.businessService.findAll();
    return businesses;
  }

  // Admin user
  @Post('admins/update')
  @UseGuards(RolesGuard)
  @Roles('creator')
  @UseInterceptors(FileInterceptor('new_photo'))
  async updateAdmin(
    @UploadedFile() photo: Express.Multer.File,
    @Body() data: any,
  ): Promise<User> {
    return await this.userService.update(data, photo);
  }

  @Put(':id')
  @UseGuards(RolesGuard)
  @Roles('creator')
  update(@Param('id') id: string, @Body() dto: any) {
    return this.businessService.update(id, dto);
  }

  // Admin user
  @Delete('admins/:id')
  @UseGuards(RolesGuard)
  @Roles('creator')
  removeAdmin(@Param('id') id: string) {
    return this.userService.remove(id);
  }

  @Delete(':id')
  @UseGuards(RolesGuard)
  @Roles('creator')
  remove(@Param('id') id: string) {
    return this.businessService.remove(id);
  }
}
