// auth.middleware.ts

import Admin from '@/modules/admins/entities/admin.entity';
import { AdminsService } from '@/modules/admins/services/admins.service';
import { AuthService } from '@/modules/auth/auth.service';
import AppResponse from '@/response/app-response';
import {
  ForbiddenException,
  HttpStatus,
  Injectable,
  NestMiddleware,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { NextFunction, Request, Response } from 'express';
import { PermissionService } from '../services/permission.service';

@Injectable()
export class AuthorizationMiddleware implements NestMiddleware {
  constructor(
    private readonly jwtService: JwtService,
    private readonly adminService: AdminsService,
    private readonly authService: AuthService,
    private readonly permissionService: PermissionService,
  ) {}

  async use(req: Request, res: Response, next: NextFunction) {
    const admin: Admin | undefined = ({} = req['admin']);

    if (!admin) {
      next(
        new UnauthorizedException(
          AppResponse.toResponse(null, {
            message: 'Un authentication',
            status_code: HttpStatus.UNAUTHORIZED,
          }),
        ),
      );

      return;
    }

    if (admin.is_system_account) {
      next();
      return;
    }

    const permissions = await this.permissionService.getPermissionsByAdmin(
      admin.id,
    );

    if (!permissions.some((item) => item.name === req.method)) {
      next(
        new ForbiddenException(
          AppResponse.toResponse(null, {
            message: 'Forbidden',
            status_code: HttpStatus.FORBIDDEN,
          }),
        ),
      );
      return;
    }

    next();
  }
}
