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

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

@Injectable()
export class FreightMeService {
  constructor(@InjectDataSource() private readonly dataSource: DataSource) {}

  /**
   * The JWT session snapshot has no position TYPE, but the backoffice needs it
   * (GL sub-positions are identified by type key). Resolved live from IAM.
   */
  private async lookupPositionType(
    positionId: string | undefined,
  ): Promise<{ key: string; name: unknown } | null> {
    if (!positionId) return null;
    try {
      const rows: { key: string; name: unknown }[] = await this.dataSource.query(
        `SELECT pt.key, pt.name
           FROM iam.positions p
           JOIN iam.position_types pt ON pt.id = p.position_type_id
          WHERE p.id = $1`,
        [positionId],
      );
      return rows[0] ?? null;
    } catch {
      return null; // iam schema unreachable — degrade to the old payload shape
    }
  }

  async getEnrichedProfile(user: TCurrentUser) {
    const positionType = await this.lookupPositionType(
      user.employee?.position?.id,
    );

    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 ?? [],
                    positionType,
                  },
                ]
              : [],
          },
        ]
      : [];

    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,
    };
  }
}
