import { RequestWithAuth, enforceTenant, enforceUser, mockUser } from "@erp/auth/api";
import { ModuleParams, validateRequest } from "@erp/core/api";
import { SendInvoiceByIdRequestSchema } from "@erp/verifactu/common";
import { ILogger } from "@repo/rdx-logger";
import { Application, NextFunction, Request, Response, Router } from "express";
import { Sequelize } from "sequelize";
import { buildVerifactuDependencies } from "../dependencies";
import { SendInvoiceVerifactuController } from "./controllers";

export const verifactuRouter = (params: ModuleParams) => {
  const { app, baseRoutePath, logger } = params as {
    app: Application;
    database: Sequelize;
    baseRoutePath: string;
    logger: ILogger;
  };

  const deps = buildVerifactuDependencies(params);

  const router: Router = Router({ mergeParams: true });

  // 🔐 Autenticación + Tenancy para TODO el router
  if (process.env.NODE_ENV === "development") {
    router.use(
      (req: Request, res: Response, next: NextFunction) =>
        mockUser(req as RequestWithAuth, res, next) // Debe ir antes de las rutas protegidas
    );
  }

  router.use([
    (req: Request, res: Response, next: NextFunction) =>
      enforceUser()(req as RequestWithAuth, res, next), // Debe ir antes de las rutas protegidas

    (req: Request, res: Response, next: NextFunction) =>
      enforceTenant()(req as RequestWithAuth, res, next), // Debe ir antes de las rutas protegidas
  ]);

  // ----------------------------------------------

  router.get(
    "/:invoice_id/sendVerifactu",
    //checkTabContext,
    validateRequest(SendInvoiceByIdRequestSchema, "params"),
    (req: Request, res: Response, next: NextFunction) => {
      const { listServices } = deps;
      const useCase = deps.build.send();

      logger.info(listServices());

      const controller = new SendInvoiceVerifactuController(useCase);
      return controller.execute(req, res, next);
    }
  );

  app.use(`${baseRoutePath}/verifactu`, router);
};
