import { stateName } from '@/lib/domain/states'
import { canSeePermitCost, redactCostsForPilot } from '@/lib/domain/permit-cost'
import type { Permit } from '@/types/db'

export function permitScopedQuestion(question: string, stateCode: string | null, permit: Permit | null, role: string): string {
  if (!stateCode && !permit) return question
  const scope = permit ? {
    workspace_permit_id: permit.id, state: stateName(permit.state_code), state_code: permit.state_code,
    permit_number: permit.permit_number, effective_date: permit.effective_date, expiration_date: permit.expiration_date,
    width_in: permit.permit_width_in, height_in: permit.permit_height_in,
    length_in: permit.permit_length_in, weight_lbs: permit.permit_weight_lbs,
    // Operational extraction fields only. Route files and costs are not passed here.
    restrictions: permit.extraction?.restrictions, curfews: permit.extraction?.curfews, escorts: permit.extraction?.escorts,
  } : { state_code: stateCode, state: stateName(stateCode) }
  const context = JSON.stringify(scope)
  return `Answer the following question only for ${permit ? 'the selected permit identified below. Do not substitute another permit for the same state' : 'the selected state'}. Use this permit's conditions first, then state provisions and internal state notes. Identify the sources used; say when the selected permit does not contain enough information.\nSelected scope: ${canSeePermitCost(role) ? context : redactCostsForPilot(context)}\nQuestion: ${question}`
}
