/**
 * Agent Action Logger
 * Records all autonomous agent actions for full audit trail
 */

import prisma from '@/lib/db';
import { AgentContext, AgentActionType, AnomalyResult } from './types';

export interface LogActionParams {
  context: AgentContext;
  actionType: AgentActionType;
  targetEntity: string;
  targetId: string;
  inputData?: Record<string, unknown>;
  outputData?: Record<string, unknown>;
  status?: 'pending' | 'completed' | 'failed' | 'requires_review';
  confidence?: number;
  anomaly?: AnomalyResult;
  executionTimeMs?: number;
  error?: string;
}

// Simple log action params for standalone operations (dunning, reconciliation)
export interface SimpleLogActionParams {
  actionType: AgentActionType;
  targetEntity: string;
  targetId: string;
  input?: Record<string, unknown>;
  output?: Record<string, unknown>;
  confidence?: number;
  anomalyDetected?: boolean;
  anomalyType?: string;
}

export async function logAgentAction(params: LogActionParams): Promise<string> {
  const {
    context,
    actionType,
    targetEntity,
    targetId,
    inputData = {},
    outputData = {},
    status = 'completed',
    confidence = 1.0,
    anomaly,
    executionTimeMs,
    error,
  } = params;

  const action = await prisma.agentAction.create({
    data: {
      executionId: context.executionId,
      agentName: context.agentName,
      actionType,
      targetEntity,
      targetId,
      inputData: JSON.parse(JSON.stringify(inputData)),
      outputData: JSON.parse(JSON.stringify(outputData)),
      status,
      confidence,
      anomalyDetected: anomaly?.detected || false,
      anomalyDetails: anomaly ? JSON.parse(JSON.stringify(anomaly)) : undefined,
      executionTimeMs,
      error,
    },
  });

  return action.id;
}

// Simplified logging for standalone operations (dunning, reconciliation)
export async function logSimpleAction(params: SimpleLogActionParams): Promise<string> {
  const {
    actionType,
    targetEntity,
    targetId,
    input = {},
    output = {},
    confidence = 1.0,
    anomalyDetected = false,
    anomalyType,
  } = params;

  const action = await prisma.agentAction.create({
    data: {
      executionId: `standalone-${Date.now()}`,
      agentName: 'SystemAgent',
      actionType,
      targetEntity,
      targetId,
      inputData: JSON.parse(JSON.stringify(input)),
      outputData: JSON.parse(JSON.stringify(output)),
      status: 'completed',
      confidence,
      anomalyDetected,
      anomalyDetails: anomalyType ? JSON.parse(JSON.stringify({ type: anomalyType })) : undefined,
    },
  });

  return action.id;
}

export async function markActionReviewed(
  actionId: string,
  reviewedBy: string,
  decision: 'approved' | 'rejected' | 'modified'
): Promise<void> {
  await prisma.agentAction.update({
    where: { id: actionId },
    data: {
      humanReviewed: true,
      reviewedBy,
      reviewedAt: new Date(),
      reviewDecision: decision,
    },
  });
}

export async function getOrderActions(orderId: string) {
  return prisma.agentAction.findMany({
    where: {
      OR: [
        { targetEntity: 'order', targetId: orderId },
        { executionId: { startsWith: orderId } },
      ],
    },
    orderBy: { createdAt: 'asc' },
  });
}

export async function getAnomalousActions(limit = 50) {
  return prisma.agentAction.findMany({
    where: {
      anomalyDetected: true,
      humanReviewed: false,
    },
    orderBy: { createdAt: 'desc' },
    take: limit,
  });
}
