// WAPL Pattern Library Service

import prisma from '@/shared/database/prisma';
import { Prisma } from '@prisma/client';
import { WAPLPattern } from './types';
import { circularFXPattern } from './patterns/circular-fx.pattern';
import { cbdcLayeringPattern } from './patterns/cbdc-layering.pattern';
import { logger } from '@/infrastructure/monitoring/logger';
import { v4 as uuidv4 } from 'uuid';


export class PatternLibraryService {
  /**
   * Initialize default patterns
   */
  async initializeDefaultPatterns(): Promise<void> {
    const defaultPatterns = [
      circularFXPattern,
      cbdcLayeringPattern,
    ];

    for (const pattern of defaultPatterns) {
      await prisma.wapl_patterns.upsert({
        where: { patternCode: pattern.patternCode },
        create: {
          id: pattern.id || uuidv4(),
          patternCode: pattern.patternCode,
          name: pattern.name,
          description: pattern.description,
          patternDefinition: pattern.patternDefinition,
          severity: pattern.severity,
          status: pattern.status,
          createdAt: new Date(),
          updatedAt: new Date(),
        },
        update: {
          name: pattern.name,
          description: pattern.description,
          patternDefinition: pattern.patternDefinition,
          severity: pattern.severity,
          status: pattern.status,
        },
      });
    }

    logger.info(`Initialized ${defaultPatterns.length} default WAPL patterns`);
  }

  /**
   * Get all active patterns
   */
  async getActivePatterns(): Promise<WAPLPattern[]> {
    const patterns = await prisma.wapl_patterns.findMany({
      where: { status: 'ACTIVE' },
      orderBy: { patternCode: 'asc' },
    });

    return patterns.map((p) => this.mapToWAPLPattern(p));
  }

  /**
   * Get pattern by code
   */
  async getPattern(patternCode: string): Promise<WAPLPattern | null> {
    const pattern = await prisma.wapl_patterns.findUnique({
      where: { patternCode },
    });

    if (!pattern) {
      return null;
    }

    return this.mapToWAPLPattern(pattern);
  }

  /**
   * Create or update pattern
   */
  async upsertPattern(pattern: Partial<WAPLPattern>): Promise<WAPLPattern> {
    const upserted = await prisma.wapl_patterns.upsert({
      where: { patternCode: pattern.patternCode! },
      create: {
        id: pattern.id || uuidv4(),
        patternCode: pattern.patternCode!,
        name: pattern.name!,
        description: pattern.description!,
        patternDefinition: pattern.patternDefinition!,
        severity: pattern.severity || 'MEDIUM',
        status: pattern.status || 'DRAFT',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      update: {
        name: pattern.name,
        description: pattern.description,
        patternDefinition: pattern.patternDefinition,
        severity: pattern.severity,
        status: pattern.status,
      },
    });

    logger.info(`Upserted WAPL pattern: ${upserted.patternCode}`);

    return this.mapToWAPLPattern(upserted);
  }

  private mapToWAPLPattern(pattern: any): WAPLPattern {
    return {
      id: pattern.id,
      patternCode: pattern.patternCode,
      name: pattern.name,
      description: pattern.description,
      patternDefinition: pattern.patternDefinition,
      severity: pattern.severity,
      status: pattern.status,
    };
  }
}

export const patternLibraryService = new PatternLibraryService();

