// MSGF Tier Service
// Governance tier management and authority delegation

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';


export interface CreateTierRequest {
  tierNumber: 0 | 1 | 2 | 3;
  tierName: string;
  description: string;
  authorityScope: Record<string, unknown>;
}

export interface CreateDelegationRequest {
  fromTierId: string;
  toTierId: string;
  delegationType: string;
  authorityScope: Record<string, unknown>;
}

export class MsgfTierService {
  /**
   * Create governance tier
   */
  async createTier(request: CreateTierRequest) {
    const tierId = `TIER-${request.tierNumber}-${uuidv4()}`;

    const tier = await prisma.governanceTier.create({
      data: {
        tierId,
        tierNumber: request.tierNumber,
        tierName: request.tierName,
        description: request.description,
        authorityScope: request.authorityScope,
        status: 'active',
      },
    });

    return tier;
  }

  /**
   * Get tier by ID
   */
  async getTier(tierId: string) {
    const tier = await prisma.governanceTier.findUnique({
      where: { tierId },
      include: {
        delegations: {
          include: {
            fromTier: true,
            toTier: true,
          },
        },
      },
    });

    if (!tier) {
      throw new Error(`Tier not found: ${tierId}`);
    }

    return tier;
  }

  /**
   * Get all tiers
   */
  async getAllTiers() {
    return prisma.governanceTier.findMany({
      where: { status: 'active' },
      include: {
        _count: {
          select: {
            delegations: true,
          },
        },
      },
      orderBy: {
        tierNumber: 'asc',
      },
    });
  }

  /**
   * Create tier delegation
   */
  async createDelegation(request: CreateDelegationRequest) {
    const delegationId = `DELEG-${uuidv4()}`;

    const delegation = await prisma.tierDelegation.create({
      data: {
        delegationId,
        fromTierId: request.fromTierId,
        toTierId: request.toTierId,
        delegationType: request.delegationType,
        authorityScope: request.authorityScope,
        status: 'active',
      },
    });

    return delegation;
  }

  /**
   * Get delegations for a tier
   */
  async getDelegations(tierId: string, direction: 'from' | 'to' = 'from') {
    const where = direction === 'from' ? { fromTierId: tierId } : { toTierId: tierId };

    return prisma.tierDelegation.findMany({
      where: {
        ...where,
        status: 'active',
      },
      include: {
        fromTier: true,
        toTier: true,
      },
    });
  }
}

export const msgfTierService = new MsgfTierService();

