import { Injectable } from '@nestjs/common';
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';

import {
  collectPermissionKeys,
  isSuperAdmin,
} from '../../common/freight-permission.util';
import { PERMISSIONS_CATALOG } from '../../seed/freight-permissions.registry';

@Injectable()
export class FreightMeService {
  getEnrichedProfile(user: TCurrentUser) {
    const employee = user.employee
      ? [
          {
            id: user.employee.id,
            organizationId: user.employee.organizationId,
            unitId: user.employee.unitId,
            name: user.employee.name,
            positions: user.employee.position
              ? [
                  {
                    id: user.employee.position.id,
                    key: user.employee.position.key,
                    employeePositionId: user.employee.position.employeePositionId,
                    name: user.employee.position.name,
                    isDelegate: user.employee.position.isDelegate,
                    parentPositionId: user.employee.position.parentPositionId,
                    permissions: user.employee.position.permissions ?? [],
                  },
                ]
              : [],
          },
        ]
      : [];

    const permissionKeys = collectPermissionKeys(user);

    return {
      id: user.id,
      email: user.email,
      name: user.name,
      username: user.username,
      phoneNumber: user.phoneNumber,
      userType: user.userType,
      status: user.status,
      hasFinishedRegistration: user.hasFinishedRegistration,
      hasFinishedDMSOnboarding: user.hasFinishedDMSOnboarding,
      roles: user.roles,
      permissions: user.permissions,
      employee,
      permissionKeys,
      isSuperAdmin: isSuperAdmin(user),
      permissionsCatalog: PERMISSIONS_CATALOG,
    };
  }
}
