// 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.meta_sovereign_councils.create({
      data: {
        id: uuidv4(),
        councilId,
        councilType: request.councilType,
        name: request.name,
        description: request.description,
        authorityLevel: 'Tier 0 - Meta-Sovereign',
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return council;
  }

  /**
   * Get council by ID
   */
  async getCouncil(councilId: string) {
    const council = await prisma.meta_sovereign_councils.findUnique({
      where: { councilId },
      include: {
        meta_sovereign_council_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.meta_sovereign_councils.findMany({
      where,
      include: {
        members: true,
        _count: {
          select: {
            meta_sovereign_meta_sovereign_policies: true,
            decisions: true,
          },
        },
      },
    });
  }

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

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

    const member = await prisma.meta_sovereign_council_members.create({
      data: {
        id: uuidv4(),
        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(),
        createdAt: new Date(),
        updatedAt: 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.meta_sovereign_decisions.create({
      data: {
        decisionId,
        councilId,
        decisionType,
        decisionContent,
        status: 'pending',
      },
    });

    return decision;
  }

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

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

export const msgfCouncilService = new MsgfCouncilService();

