// DBIS Constitution Service
// Article retrieval, versioning, legal personality checks

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


export interface ConstitutionArticleData {
  articleNumber: string;
  articleTitle: string;
  section?: string;
  content: string;
  effectiveDate: Date;
  expiryDate?: Date;
  metadata?: Record<string, unknown>;
}

export class ConstitutionService {
  /**
   * Get article by number and version
   */
  async getArticle(
    articleNumber: string,
    version?: number
  ): Promise<ConstitutionArticleData | null> {
    const where: { articleNumber: string; status: string; version?: number } = {
      articleNumber,
      status: 'active',
    };

    if (version) {
      where.version = version;
    }

    const article = await prisma.constitution_articles.findFirst({
      where,
      orderBy: version ? undefined : { version: 'desc' },
    });

    if (!article) {
      return null;
    }

    return {
      articleNumber: article.articleNumber,
      articleTitle: article.articleTitle,
      section: article.section || undefined,
      content: article.content,
      effectiveDate: article.effectiveDate,
      expiryDate: article.expiryDate || undefined,
      metadata: (article.metadata as Record<string, unknown>) || undefined,
    };
  }

  /**
   * Get all articles
   */
  async getAllArticles(includeArchived = false): Promise<ConstitutionArticleData[]> {
    const where: { status?: string } = {};
    if (!includeArchived) {
      where.status = 'active';
    }

    const articles = await prisma.constitution_articles.findMany({
      where,
      orderBy: [{ articleNumber: 'asc' }, { version: 'desc' }],
    });

    return articles.map((article) => ({
      articleNumber: article.articleNumber,
      articleTitle: article.articleTitle,
      section: article.section || undefined,
      content: article.content,
      effectiveDate: article.effectiveDate,
      expiryDate: article.expiryDate || undefined,
      metadata: (article.metadata as Record<string, unknown>) || undefined,
    }));
  }

  /**
   * Create new article version
   */
  async createArticleVersion(
    data: ConstitutionArticleData
  ): Promise<{ id: string; version: number }> {
    // Get latest version
    const latest = await prisma.constitution_articles.findFirst({
      where: { articleNumber: data.articleNumber },
      orderBy: { version: 'desc' },
    });

    const newVersion = latest ? latest.version + 1 : 1;

    // Archive previous version if exists
    if (latest) {
      await prisma.constitution_articles.updateMany({
        where: {
          articleNumber: data.articleNumber,
          status: 'active',
        },
        data: {
          status: 'superseded',
        },
      });
    }

    const article = await prisma.constitution_articles.create({
      data: {
        id: uuidv4(),
        articleNumber: data.articleNumber,
        articleTitle: data.articleTitle,
        section: data.section,
        content: data.content,
        version: newVersion,
        effectiveDate: data.effectiveDate,
        expiryDate: data.expiryDate,
        metadata: (data.metadata || {}) as Prisma.InputJsonValue,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return { id: article.id, version: article.version };
  }

  /**
   * Check legal personality status
   */
  async checkLegalPersonality(): Promise<{
    hasLegalPersonality: boolean;
    canEnterContracts: boolean;
    canHoldAssets: boolean;
    canSupervise: boolean;
    hasImmunity: boolean;
  }> {
    // Check Article I (Legal Personality)
    const articleI = await this.getArticle('I');
    if (!articleI) {
      return {
        hasLegalPersonality: false,
        canEnterContracts: false,
        canHoldAssets: false,
        canSupervise: false,
        hasImmunity: false,
      };
    }

    // Article I establishes legal personality
    return {
      hasLegalPersonality: true,
      canEnterContracts: true,
      canHoldAssets: true,
      canSupervise: true,
      hasImmunity: true, // Functional immunity under Charter
    };
  }

  /**
   * Verify mandate compliance
   */
  async verifyMandate(operation: string): Promise<boolean> {
    // Check Article II (Mandates)
    const articleII = await this.getArticle('II');
    if (!articleII) {
      return false;
    }

    // Verify operation aligns with DBIS mandates
    const mandates = [
      'monetary_stability',
      'master_ledger',
      'cross_border_settlement',
      'cbdc_interoperability',
      'compliance_enforcement',
    ];

    // In production, this would parse article content and verify
    // For now, return true if article exists
    return true;
  }
}

export const constitutionService = new ConstitutionService();

