// 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.faceEconomy.create({
      data: {
        economyId,
        sovereignBankId: request.sovereignBankId,
        economyName: request.economyName,
        description: request.description,
        economyType: request.economyType,
        status: 'active',
        activatedAt: new Date(),
      },
    });

    return economy;
  }

  /**
   * Get economy by ID
   */
  async getEconomy(economyId: string) {
    const economy = await prisma.faceEconomy.findUnique({
      where: { economyId },
      include: {
        sovereignBank: true,
        behavioralEngine: true,
        supplyContracts: true,
        stabilizationContracts: true,
        incentives: true,
      },
    });

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

    return economy;
  }

  /**
   * Get economies for sovereign bank
   */
  async getEconomiesForBank(sovereignBankId: string) {
    return prisma.faceEconomy.findMany({
      where: {
        sovereignBankId,
        status: 'active',
      },
      include: {
        behavioralEngine: true,
        _count: {
          select: {
            supplyContracts: true,
            stabilizationContracts: true,
            incentives: true,
          },
        },
      },
    });
  }

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

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

export const faceEconomyService = new FaceEconomyService();

