import {
  Body,
  Controller,
  ForbiddenException,
  NotFoundException,
  Put,
} from '@nestjs/common';
import { UserRepo } from '@models/users/repos/user.repo';
import { ChangePasswordDTO, CurrentUser } from '@studio-m/app-types';
import {
  comparePassword,
  hashPassword,
} from '@models/users/functions/password.functions';

@Controller('users')
export class ChangePassword {
  constructor(private userRepo: UserRepo) {}

  @Put('change-password')
  async execute(@Body() req: CurrentUser<ChangePasswordDTO>) {
    const persistedUser = await this.userRepo.findById(req.currentUser.id);

    if (!persistedUser) {
      throw new NotFoundException();
    }

    if (!(await comparePassword(req.oldPassword, persistedUser.password))) {
      throw new ForbiddenException();
    }

    persistedUser.password = await hashPassword(req.password);

    await this.userRepo.update(persistedUser);
  }
}
