// Settlement Law Service
// Article enforcement and validation

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


export interface ArticleRequest {
  articleNumber: string;
  articleTitle: string;
  content: string;
  principle?: string; // Principle 1, 2, or 3
  effectiveDate: Date;
}

export interface ArticleValidationRequest {
  transactionId: string;
  articleNumber: string;
}

export class SettlementLawService {
  /**
   * Create settlement law article
   */
  async createArticle(request: ArticleRequest): Promise<{ articleId: string }> {
    const articleId = `ARTICLE-${uuidv4()}`;

    const article = await prisma.settlementLawArticle.create({
      data: {
        articleId,
        articleNumber: request.articleNumber,
        articleTitle: request.articleTitle,
        content: request.content,
        principle: request.principle || null,
        effectiveDate: request.effectiveDate,
        status: 'active',
      },
    });

    return {
      articleId: article.articleId,
    };
  }

  /**
   * Get article by number
   */
  async getArticle(articleNumber: string): Promise<any | null> {
    const article = await prisma.settlementLawArticle.findFirst({
      where: {
        articleNumber,
        status: 'active',
      },
      orderBy: { version: 'desc' },
    });

    return article;
  }

  /**
   * Validate transaction against article
   */
  async validateTransaction(
    request: ArticleValidationRequest
  ): Promise<{ valid: boolean; article?: any }> {
    const article = await this.getArticle(request.articleNumber);

    if (!article) {
      return { valid: false };
    }

    // In production, would perform detailed validation based on article content
    // For now, just check if article exists and is active
    return {
      valid: article.status === 'active',
      article,
    };
  }

  /**
   * Get all active articles
   */
  async getActiveArticles(): Promise<any[]> {
    const articles = await prisma.settlementLawArticle.findMany({
      where: { status: 'active' },
      orderBy: { articleNumber: 'asc' },
    });

    return articles;
  }

  /**
   * Get articles by principle
   */
  async getArticlesByPrinciple(principle: string): Promise<any[]> {
    const articles = await prisma.settlementLawArticle.findMany({
      where: {
        principle,
        status: 'active',
      },
      orderBy: { articleNumber: 'asc' },
    });

    return articles;
  }
}

export const settlementLawService = new SettlementLawService();

