/**
 * ${BRAND.companyName} Secure Vault API
 * 
 * Stores and retrieves encrypted sensitive data.
 * All data is encrypted at rest using AES-256-GCM.
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { encrypt, decrypt } from '@/lib/gfs/crypto';
import { BRAND } from '@/lib/white-label/constants';

export const dynamic = 'force-dynamic';

// Store encrypted credential
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, name, value, category = 'credential' } = body;

    if (action === 'store') {
      if (!name || !value) {
        return NextResponse.json({ error: 'name and value required' }, { status: 400 });
      }

      // Encrypt the value
      const encryptedValue = encrypt(JSON.stringify(value));

      // Store in GhostMemory with special category
      const memory = await prisma.ghostMemory.upsert({
        where: { category_key: { category: `vault_${category}`, key: name } },
        create: {
          category: `vault_${category}`,
          key: name,
          value: { encrypted: encryptedValue, storedAt: new Date().toISOString() },
          confidence: 1.0,
          source: 'secure_vault',
        },
        update: {
          value: { encrypted: encryptedValue, storedAt: new Date().toISOString() },
        },
      });

      // Log the evolution (without the actual value)
      await prisma.ghostEvolution.create({
        data: {
          type: 'memory_add',
          description: `Secured: vault_${category}/${name}`,
          after: { name, category, secured: true },
          reason: 'Encrypted credential storage',
          confidence: 1.0,
        },
      });

      return NextResponse.json({ 
        success: true, 
        message: `Credential '${name}' stored securely`,
        id: memory.id 
      });
    }

    if (action === 'retrieve') {
      if (!name) {
        return NextResponse.json({ error: 'name required' }, { status: 400 });
      }

      const memory = await prisma.ghostMemory.findUnique({
        where: { category_key: { category: `vault_${category}`, key: name } },
      });

      if (!memory) {
        return NextResponse.json({ error: 'Credential not found' }, { status: 404 });
      }

      // Decrypt
      const memValue = memory.value as { encrypted: string };
      const decrypted = JSON.parse(decrypt(memValue.encrypted));

      // Update access count
      await prisma.ghostMemory.update({
        where: { id: memory.id },
        data: { usageCount: memory.usageCount + 1, lastUsed: new Date() },
      });

      return NextResponse.json({ success: true, value: decrypted });
    }

    if (action === 'list') {
      // List all vault entries (names only, no values)
      const memories = await prisma.ghostMemory.findMany({
        where: { category: { startsWith: 'vault_' } },
        select: { key: true, category: true, createdAt: true, usageCount: true },
      });

      return NextResponse.json({ 
        credentials: memories.map((m: any) => ({
          name: m.key,
          category: m.category.replace('vault_', ''),
          createdAt: m.createdAt,
          accessCount: m.usageCount,
        }))
      });
    }

    if (action === 'delete') {
      if (!name) {
        return NextResponse.json({ error: 'name required' }, { status: 400 });
      }

      await prisma.ghostMemory.delete({
        where: { category_key: { category: `vault_${category}`, key: name } },
      });

      return NextResponse.json({ success: true, message: `Credential '${name}' deleted` });
    }

    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error('Vault error:', error);
    return NextResponse.json({ 
      error: 'Vault operation failed',
      details: error instanceof Error ? error.message : 'Unknown error'
    }, { status: 500 });
  }
}

// GET - List stored credentials (names only)
export async function GET() {
  try {
    const memories = await prisma.ghostMemory.findMany({
      where: { category: { startsWith: 'vault_' } },
      select: { key: true, category: true, createdAt: true, usageCount: true },
    });

    return NextResponse.json({ 
      credentials: memories.map((m: any) => ({
        name: m.key,
        category: m.category.replace('vault_', ''),
        createdAt: m.createdAt,
        accessCount: m.usageCount,
      }))
    });
  } catch (error) {
    console.error('Vault GET error:', error);
    return NextResponse.json({ error: 'Failed to list credentials' }, { status: 500 });
  }
}
