/**
 * Memory System Configuration API
 * 
 * Manages the customer opt-in settings for the Familiar memory system.
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

// GET - Get current configuration
export async function GET() {
  try {
    let config = await prisma.memorySystemConfig.findFirst({
      where: { organizationId: 'default' }
    });

    // Create default config if not exists
    if (!config) {
      config = await prisma.memorySystemConfig.create({
        data: {
          organizationId: 'default',
          enabled: false,
          retentionDays: 365,
          maxMemoriesPerAgent: 10000,
          maxInsightsPerDay: 100,
          autoCleanupEnabled: true,
          crossAgentSharingEnabled: true,
          mcpEndpointEnabled: false,
          llmInsightsEnabled: true,
          proactiveAlertsEnabled: true,
          sensitiveDataFiltering: true,
          auditLogging: true,
          customRules: []
        }
      });
    }

    return NextResponse.json({ success: true, config });
  } catch (error: any) {
    console.error('Error getting memory config:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// POST - Update configuration
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    const config = await prisma.memorySystemConfig.upsert({
      where: { organizationId: 'default' },
      update: {
        ...body,
        updatedAt: new Date()
      },
      create: {
        organizationId: 'default',
        enabled: body.enabled ?? false,
        retentionDays: body.retentionDays ?? 365,
        maxMemoriesPerAgent: body.maxMemoriesPerAgent ?? 10000,
        maxInsightsPerDay: body.maxInsightsPerDay ?? 100,
        autoCleanupEnabled: body.autoCleanupEnabled ?? true,
        crossAgentSharingEnabled: body.crossAgentSharingEnabled ?? true,
        mcpEndpointEnabled: body.mcpEndpointEnabled ?? false,
        llmInsightsEnabled: body.llmInsightsEnabled ?? true,
        proactiveAlertsEnabled: body.proactiveAlertsEnabled ?? true,
        sensitiveDataFiltering: body.sensitiveDataFiltering ?? true,
        auditLogging: body.auditLogging ?? true,
        customRules: body.customRules ?? []
      }
    });

    return NextResponse.json({ success: true, config });
  } catch (error: any) {
    console.error('Error updating memory config:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
