import { Response } from '../../../models/Response.js'
import { Headers } from '../../../lib/headers/Headers.js'
import { isRedirect, STATUS_UNAUTHORIZED } from '../constants.js'

export interface ResponseProcessingContext {
  status: number
  currentResponse?: Response
  currentHeaders?: Headers
  followRedirects: boolean
  auth?: { method: string }
  aborted: boolean
}

export interface ResponseProcessingResult {
  shouldContinue: boolean
  action: 'redirect' | 'auth' | 'publish' | 'abort'
  data?: Record<string, unknown>
}

/**
 * Process the response and determine the next action
 */
export function processResponse(context: ResponseProcessingContext): ResponseProcessingResult {
  const { status, followRedirects, auth, aborted } = context

  if (aborted) {
    return { shouldContinue: false, action: 'abort' }
  }

  // Handle redirects
  if (isRedirect(status)) {
    if (followRedirects) {
      return { shouldContinue: false, action: 'redirect', data: { status } }
    }
  }

  // Handle authentication challenges
  if (status === STATUS_UNAUTHORIZED && auth) {
    if (auth.method === 'ntlm') {
      return { shouldContinue: false, action: 'auth', data: { method: 'ntlm' } }
    }
  }

  // Normal response - publish it
  return { shouldContinue: false, action: 'publish' }
}
