import { AuthUser } from "@/contexts/auth/domain";
import { GetDealerByUserUseCase } from "@/contexts/sales/application";
import * as express from "express";
import { registerDealerRepository } from "../../Dealer.repository";
import { ISalesContext } from "../../Sales.context";

interface AuthenticatedRequest extends express.Request {
  user?: AuthUser;
}

export const getDealerMiddleware = async (
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) => {
  const _req = req as AuthenticatedRequest;
  const user = <AuthUser>_req.user;
  const context: ISalesContext = res.locals.context;

  registerDealerRepository(context);

  try {
    const dealerOrError = await new GetDealerByUserUseCase(context).execute({
      userId: user.id,
    });

    if (dealerOrError.isFailure) {
      return res.status(500).json().send();
      //return this._handleExecuteError(result.error);
    }

    context.dealer = dealerOrError.object;

    return next();
  } catch (e: unknown) {
    //return this.fail(e as IServerError);
    return res.status(500).json().send();
  }
};
