/**
 * POST /api/offers/conditions
 * Body: { source: 'lead'|'partner', recordId, docType: 'quote'|'contract'|'forecast', payload }
 * Persists the current modal state as the record's offer_conditions WITHOUT
 * sending anything (no email, no PDF, no attachment) — a "save draft" action so
 * pricing/services entered now can be picked up again later. Reuses the exact
 * persistable shape a real send would store (see server/utils/offers/offerConditions.ts).
 */
import refreshTokenHelper from '../../../utils/refreshTokenHelper'
import errorHandlingHelper from '../../../utils/errorHandlingHelper'
import forceLogoutHelper from '../../../utils/forceLogoutHelper'
import { saveOfferConditions, conditionsFromQuotePayload, conditionsFromContractPayload } from '../../../utils/offers/offerConditions'
import { conditionsFromForecastPayload } from '../../../utils/offers/forecastPdf'

const handleFunc = async (event: any, authToken: string | null = null) => {
  const token = authToken ?? await getTokenHelper(event)
  if (!token) return { status: 401, message: 'Not authenticated' }

  const body = await readBody(event)
  const source = body?.source === 'lead' ? 'lead' : 'partner'
  const recordId = Number(body?.recordId)
  const docType = body?.docType === 'contract' ? 'contract' : (body?.docType === 'forecast' ? 'forecast' : 'quote')
  if (!(recordId > 0)) return { status: 400, message: 'recordId required' }

  const payload = body?.payload || {}
  const conditions = docType === 'contract'
    ? conditionsFromContractPayload(payload)
    : (docType === 'forecast' ? conditionsFromForecastPayload(payload) : conditionsFromQuotePayload(payload))
  await saveOfferConditions(event, token, source, recordId, docType, conditions)

  return { status: 200, message: 'Draft saved' }
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  try {
    data = await handleFunc(event)
  } catch (err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }
  return data
})
