// MSGF Council Service
// Meta-Sovereign Assembly (MSA), Universal Monetary Court (UMC), Autonomous Economic Steering Unit (AESU)

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';


export interface CreateCouncilRequest {
  councilType: 'MSA' | 'UMC' | 'AESU';
  name: string;
  description: string;
}

export interface AddMemberRequest {
  councilId: string;
  sovereignBankId?: string;
  memberName: string;
  memberRole: string;
  votingWeight?: number;
}

export class MsgfCouncilService {
  /**
   * Create meta-sovereign council
   */
  async createCouncil(request: CreateCouncilRequest) {
    const councilId = `MSGF-${request.councilType}-${uuidv4()}`;

    const council = await prisma.metaSovereignCouncil.create({
      data: {
        councilId,
        councilType: request.councilType,
        name: request.name,
        description: request.description,
        authorityLevel: 'Tier 0 - Meta-Sovereign',
        status: 'active',
      },
    });

    return council;
  }

  /**
   * Get council by ID
   */
  async getCouncil(councilId: string) {
    const council = await prisma.metaSovereignCouncil.findUnique({
      where: { councilId },
      include: {
        members: {
          include: {
            sovereignBank: true,
          },
        },
        policies: true,
        decisions: true,
      },
    });

    if (!council) {
      throw new Error(`Council not found: ${councilId}`);
    }

    return council;
  }

  /**
   * Get all councils
   */
  async getAllCouncils(councilType?: string) {
    const where = councilType ? { councilType, status: 'active' } : { status: 'active' };

    return prisma.metaSovereignCouncil.findMany({
      where,
      include: {
        members: true,
        _count: {
          select: {
            policies: true,
            decisions: true,
          },
        },
      },
    });
  }

  /**
   * Add member to council
   */
  async addMember(request: AddMemberRequest) {
    const council = await prisma.metaSovereignCouncil.findUnique({
      where: { councilId: request.councilId },
    });

    if (!council) {
      throw new Error(`Council not found: ${request.councilId}`);
    }

    const member = await prisma.metaSovereignCouncilMember.create({
      data: {
        councilId: request.councilId,
        sovereignBankId: request.sovereignBankId || null,
        memberName: request.memberName,
        memberRole: request.memberRole,
        votingWeight: request.votingWeight ? new Decimal(request.votingWeight) : null,
        status: 'active',
        appointedAt: new Date(),
      },
    });

    return member;
  }

  /**
   * Create decision
   */
  async createDecision(
    councilId: string,
    decisionType: string,
    decisionContent: Record<string, unknown>
  ) {
    const decisionId = `MSGF-DEC-${uuidv4()}`;

    const decision = await prisma.metaSovereignDecision.create({
      data: {
        decisionId,
        councilId,
        decisionType,
        decisionContent,
        status: 'pending',
      },
    });

    return decision;
  }

  /**
   * Approve decision
   */
  async approveDecision(decisionId: string) {
    return prisma.metaSovereignDecision.update({
      where: { decisionId },
      data: {
        status: 'approved',
        approvedAt: new Date(),
      },
    });
  }

  /**
   * Execute decision
   */
  async executeDecision(decisionId: string) {
    return prisma.metaSovereignDecision.update({
      where: { decisionId },
      data: {
        status: 'executed',
        executedAt: new Date(),
      },
    });
  }
}

export const msgfCouncilService = new MsgfCouncilService();

