import { Injectable } from "@nestjs/common"
import { CreateOrganogramDto } from "../dto/create-organogram.dto"

import { RoleRepository } from "../../role/repositories/role.repository"
import { Role } from "../../role/entities/role.entity"
import { successResponse } from "src/common/response/response"
import { code } from "src/common/response/response.code"
import { successMessage } from "src/utils/helpers"
import { messageKey } from "src/constants/message-keys"

@Injectable()
export class OrganogramService {
  constructor(private readonly roleRepository: RoleRepository) {}

  async getOrganogram() {
    // Get all roles with their team members count
    const roles = (await this.roleRepository.getByParams({
      relations: [
        "team_member",
        "departments:id,name",
        "business_verticals:id,name",
      ],
    })) as Role[]

    // Build the organogram tree recursively
    const buildTree = async (
      parentRoleId: number | null,
    ): Promise<CreateOrganogramDto[]> => {
      // Find all roles that have this parent_role_id
      const childRoles = roles.filter(
        (role) => role?.parent_role_id === parentRoleId,
      )

      // For each child role, build its subtree
      const nodes: CreateOrganogramDto[] = []

      for (const role of childRoles) {
        const userCount = role?.team_member?.length || 0

        // Recursively get children for this role
        const children = await buildTree(role.id)

        const node: CreateOrganogramDto = {
          name: `${role?.name}${userCount > 0 ? ` (${userCount})` : ""}`,
          user_count: userCount,
          is_assistant: children.length > 0, // Set is_assistant true if role has children
          department: role?.departments,
          business_verticals: role?.business_verticals,
        }

        if (children.length > 0) {
          node.children = children
        }

        nodes.push(node)
      }

      return nodes
    }

    // Start with null parent_role_id to get root roles
    const treeData = await buildTree(null)

    return successResponse(
      code.SUCCESS,
      successMessage(messageKey.data_retrieve, {
        ":data": "organogram",
      }),
      treeData,
    )
  }
}
