import { Repository } from 'typeorm';
import { HttpException, HttpStatus } from '@nestjs/common';

interface AccountHierarchy {
  accountId: string;
  accountName: string;
  parentId: string;
  parentName: string;
}

export class AccountHierarchyHelper {
  static async getAccountHierarchy(
    accountId: string,
    r360AccountMasterRepository: Repository<any>,
  ): Promise<AccountHierarchy[]> {
    try {
      const result = await r360AccountMasterRepository.query(
        `WITH RECURSIVE RecursiveCTE AS (
                      SELECT
                        Account_360_PK,
                        Account_ID,
                        Account_Name,
                        Entity_Level,
                        CASE
                          WHEN Entity_Level = 0 OR Parent_ID is null OR Parent_ID = '' THEN Account_ID
                          ELSE Parent_ID
                        END AS Parent_ID,
                        CASE
                          WHEN Entity_Level = 0 THEN Account_Name
                          ELSE Parent_Name
                        END AS Parent_Name,
                        0 AS Level
                      FROM R360_Account_Master
                      WHERE Account_ID = '${accountId}' AND  Latest_Flag = 1 AND Active_Flag = 1
    
                      UNION
    
                      SELECT
                        m.Account_360_PK,
                        m.Account_ID,
                        m.Account_Name,
                        m.Entity_Level,
                        m.Parent_ID,
                        m.Parent_Name,
                        r.Level + 1
                      FROM R360_Account_Master m
                      JOIN RecursiveCTE r ON m.Parent_ID = r.Account_ID
                      WHERE m.Account_ID != m.Parent_ID AND m.Latest_Flag = 1 AND m.Active_Flag = 1
                    )
    
              SELECT DISTINCT
                  r.Account_ID AS accountId,
                  r.Account_Name AS accountName,
                  r.Parent_ID AS parentId,
                  r.Parent_Name AS parentName
               FROM RecursiveCTE r;
          `,
      );
      return result;
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }
}
