import {
  IUseCase,
  IUseCaseError,
  IUseCaseRequest,
  UseCaseError,
} from "@/contexts/common/application";
import { IRepositoryManager, Password } from "@/contexts/common/domain";
import { IInfrastructureError } from "@/contexts/common/infrastructure";
import { ISequelizeAdapter } from "@/contexts/common/infrastructure/sequelize";
import {
  DomainError,
  Email,
  IDomainError,
  IUpdateUser_Request_DTO,
  Language,
  Name,
  Result,
  UniqueID,
} from "@shared/contexts";
import { IUserRepository, User, UserRole } from "../domain";

export interface IUpdateUserUseCaseRequest extends IUseCaseRequest {
  id: UniqueID;
  userDTO: IUpdateUser_Request_DTO;
}

export type UpdateUserResponseOrError =
  | Result<never, IUseCaseError> // Misc errors (value objects)
  | Result<User, never>; // Success!

export class UpdateUserUseCase
  implements IUseCase<IUpdateUserUseCaseRequest, Promise<UpdateUserResponseOrError>>
{
  private _adapter: ISequelizeAdapter;
  private _repositoryManager: IRepositoryManager;

  constructor(props: { adapter: ISequelizeAdapter; repositoryManager: IRepositoryManager }) {
    this._adapter = props.adapter;
    this._repositoryManager = props.repositoryManager;
  }

  async execute(request: IUpdateUserUseCaseRequest): Promise<UpdateUserResponseOrError> {
    const { id, userDTO } = request;
    const userRepository = this._getUserRepository();

    // Comprobar que existe el user
    const idExists = await userRepository().existsUserWithId(id);
    if (!idExists) {
      const message = `User ID not found`;
      return Result.fail(
        UseCaseError.create(UseCaseError.NOT_FOUND_ERROR, message, {
          path: "id",
        })
      );
    }

    // Crear usuario
    const userOrError = this._tryCreateUserInstance(userDTO, id);

    if (userOrError.isFailure) {
      const { error: domainError } = userOrError;
      let errorCode = "";
      let message = "";

      switch (domainError.code) {
        // Errores manuales
        case User.ERROR_USER_WITHOUT_NAME:
          errorCode = UseCaseError.INVALID_INPUT_DATA;
          message = "El usuario debe tener un nombre.";
          break;

        case DomainError.INVALID_INPUT_DATA:
          errorCode = UseCaseError.INVALID_INPUT_DATA;
          message = "El usuario tiene algún dato erróneo.";
          break;

        default:
          errorCode = UseCaseError.UNEXCEPTED_ERROR;
          message = domainError.message;
          break;
      }

      return Result.fail(UseCaseError.create(errorCode, message, domainError));
    }

    return this._updateUser(userOrError.object);
  }

  private async _updateUser(user: User) {
    // Guardar el contacto
    const transaction = this._adapter.startTransaction();
    const userRepository = this._getUserRepository();
    let userRepo: IUserRepository;

    try {
      await transaction.complete(async (t) => {
        userRepo = userRepository({ transaction: t });
        await userRepo.update(user);
      });

      return Result.ok<User>(user);
    } catch (error: unknown) {
      const _error = error as IInfrastructureError;
      return Result.fail(UseCaseError.create(UseCaseError.REPOSITORY_ERROR, _error.message));
    }
  }

  private _tryCreateUserInstance(
    userDTO: IUpdateUser_Request_DTO,
    userId: UniqueID
  ): Result<User, IDomainError> {
    const nameOrError = Name.create(userDTO.name);
    if (nameOrError.isFailure) {
      return Result.fail(nameOrError.error);
    }

    const emailOrError = Email.create(userDTO.email);
    if (emailOrError.isFailure) {
      return Result.fail(emailOrError.error);
    }

    const passwordOrError = Password.createFromPlainTextPassword(userDTO.password);
    if (passwordOrError.isFailure) {
      return Result.fail(passwordOrError.error);
    }

    return User.create(
      {
        name: nameOrError.object,
        email: emailOrError.object,
        password: passwordOrError.object,
        roles: [UserRole.ROLE_USER],
        language: Language.createDefaultCode().object,
      },
      userId
    );
  }

  private _getUserRepository() {
    return this._repositoryManager.getRepository<IUserRepository>("User");
  }
}
