// FACE Economy Service
// Economy lifecycle management

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


export interface CreateFaceEconomyRequest {
  sovereignBankId: string;
  economyName: string;
  description: string;
  economyType: 'retail' | 'wholesale' | 'hybrid';
}

export class FaceEconomyService {
  /**
   * Create FACE economy
   */
  async createEconomy(request: CreateFaceEconomyRequest) {
    const economyId = `FACE-${uuidv4()}`;

    const economy = await prisma.face_economies.create({
      data: {
        id: uuidv4(),
        economyId,
        sovereignBankId: request.sovereignBankId,
        economyName: request.economyName,
        description: request.description,
        economyType: request.economyType,
        status: 'active',
        activatedAt: new Date(),
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return economy;
  }

  /**
   * Get economy by ID
   */
  async getEconomy(economyId: string) {
    const economy = await prisma.face_economies.findUnique({
      where: { economyId },
      include: {
        sovereign_banks: true,
        face_behavioral_engines: true,
        face_supply_contracts: true,
        face_stabilization_contracts: true,
        face_incentives: true,
      },
    });

    if (!economy) {
      throw new Error(`Economy not found: ${economyId}`);
    }

    return economy;
  }

  /**
   * Get economies for sovereign bank
   */
  async getEconomiesForBank(sovereignBankId: string) {
    return prisma.face_economies.findMany({
      where: {
        sovereignBankId,
        status: 'active',
      },
      include: {
        face_behavioral_engines: true,
        _count: {
          select: {
            face_supply_contracts: true,
            face_stabilization_contracts: true,
            face_incentives: true,
          },
        },
      },
    });
  }

  /**
   * Suspend economy
   */
  async suspendEconomy(economyId: string) {
    return prisma.face_economies.update({
      where: { economyId },
      data: {
        status: 'suspended',
      },
    });
  }

  /**
   * Archive economy
   */
  async archiveEconomy(economyId: string) {
    return prisma.face_economies.update({
      where: { economyId },
      data: {
        status: 'archived',
      },
    });
  }
}

export const faceEconomyService = new FaceEconomyService();

