import { AuthUser } from "@/contexts/auth/domain";
import { IServerError } from "@/contexts/common/domain/errors";
import { InfrastructureError } from "@/contexts/common/infrastructure";
import { ExpressController } from "@/contexts/common/infrastructure/express";
import { IIdentity_Response_DTO } from "@shared/contexts";
import { Request } from "express";
import { IAuthContext } from "../../../Auth.context";
import { IIdentityPresenter, IIdentityUser } from "./presenter/Identity.presenter";

interface AuthenticatedRequest extends Request {
  user?: AuthUser;
}

export class IdentityController extends ExpressController {
  private presenter: IIdentityPresenter;
  private context: IAuthContext;

  constructor(
    props: {
      presenter: IIdentityPresenter;
    },
    context: IAuthContext
  ) {
    super();

    const { presenter } = props;
    this.presenter = presenter;
    this.context = context;
  }

  async executeImpl() {
    try {
      const req = this.req as AuthenticatedRequest;
      const user = <AuthUser>req.user;

      if (!user) {
        const errorMessage = "Unexpected missing user data";
        const infraError = InfrastructureError.create(
          InfrastructureError.UNEXCEPTED_ERROR,
          errorMessage
        );
        return this.internalServerError(errorMessage, infraError);
      }

      const identityUser: IIdentityUser = user;

      return this.ok<IIdentity_Response_DTO>(this.presenter.map(identityUser, this.context));
    } catch (e: unknown) {
      return this.fail(e as IServerError);
    }
  }
}
