/**
 * Review workflow definitions
 */

import type { Document } from '@the-order/database';

export interface ReviewWorkflowInput {
  documentId: string;
  reviewerId: string;
  workflowType: 'legal' | 'finance' | 'compliance';
}

export interface ReviewWorkflowOutput {
  documentId: string;
  approved: boolean;
  comments?: string;
  nextStep?: string;
}

/**
 * Review workflow: document review → approval → publish
 * 
 * This is a simplified implementation. In production, this would use
 * Temporal or AWS Step Functions for orchestration with human-in-the-loop.
 */
export async function reviewWorkflow(
  input: ReviewWorkflowInput,
  getDocument?: (id: string) => Promise<Document | null>,
  getApprovalStatus?: (documentId: string, reviewerId: string) => Promise<boolean>
): Promise<ReviewWorkflowOutput> {
  // Step 1: Load document for review
  let document: Document | null = null;
  if (getDocument) {
    document = await getDocument(input.documentId);
    if (!document) {
      return {
        documentId: input.documentId,
        approved: false,
        comments: 'Document not found',
        nextStep: 'error',
      };
    }
  }
  
  // Step 2: Perform automated checks based on workflow type
  const automatedChecks = await performAutomatedChecks(input.documentId, input.workflowType, document);
  
  if (!automatedChecks.passed) {
    return {
      documentId: input.documentId,
      approved: false,
      comments: automatedChecks.reason,
      nextStep: 'revision',
    };
  }
  
  // Step 3: Route for human review (if required)
  // In production: await reviewService.assignReviewer(input.documentId, input.reviewerId);
  
  // Step 4: Approval decision
  let approved = false;
  if (getApprovalStatus) {
    approved = await getApprovalStatus(input.documentId, input.reviewerId);
  } else {
    // Fallback: check if document is already approved
    approved = document?.status === 'approved';
  }
  
  // Note: checkApprovalStatus function is available but not used in this simplified workflow
  // In production, it would be used for more complex approval logic
  
  // Step 5: Determine next step
  const nextStep = approved ? 'publish' : 'revision';
  
  return {
    documentId: input.documentId,
    approved,
    comments: approved ? 'Document approved' : 'Document requires revision',
    nextStep,
  };
}

/**
 * Perform automated checks based on workflow type
 */
async function performAutomatedChecks(
  _documentId: string,
  workflowType: string,
  document?: Document | null
): Promise<{ passed: boolean; reason?: string }> {
  // Basic validation checks
  
  // Check document exists and is in valid state
  if (!document) {
    return { passed: false, reason: 'Document not found' };
  }

  if (document.status === 'rejected') {
    return { passed: false, reason: 'Document has been rejected' };
  }
  
  // Legal workflow checks
  if (workflowType === 'legal') {
    // Check for required legal elements
    if (!document.classification || !['legal', 'treaty'].includes(document.classification)) {
      return { passed: false, reason: 'Document classification does not match legal workflow requirements' };
    }
    return { passed: true };
  }
  
  // Finance workflow checks
  if (workflowType === 'finance') {
    // Check for required financial elements
    if (!document.classification || document.classification !== 'finance') {
      return { passed: false, reason: 'Document classification does not match finance workflow requirements' };
    }
    return { passed: true };
  }
  
  // Compliance workflow checks
  if (workflowType === 'compliance') {
    // Check for compliance requirements
    if (!document.classification) {
      return { passed: false, reason: 'Document must be classified before compliance review' };
    }
    return { passed: true };
  }
  
  return { passed: true };
}

/**
 * Check approval status
 */
export async function checkApprovalStatus(
  documentId: string,
  _reviewerId: string,
  getDocument?: (id: string) => Promise<Document | null>
): Promise<boolean> {
  if (getDocument) {
    const document = await getDocument(documentId);
    return document?.status === 'approved';
  }
  
  // Fallback: assume not approved if we can't check
  return false;
}

