import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { connectorFaultSchema, type ConnectorFaultInput } from '@/lib/api/schemas'
import { setFault } from '@/lib/services/integration-service'

export const dynamic = 'force-dynamic'

/**
 * Inject or clear a connector fault, demo connectors only.
 *
 * Refused on a live connector: deliberately degrading a real feed is not a demonstration,
 * it is an outage. The refusal is a 409 rather than a 403 because the caller has the
 * right to do this — just not to this connector.
 */
export const POST = apiRoute<{ code: string }, ConnectorFaultInput>(
  { permission: 'integrations.simulate', bodySchema: connectorFaultSchema, limit: 30 },
  async ({ params, body, user, request }) => {
    const result = await setFault({ code: params.code, faultKind: body.faultKind ?? '' })

    if (!result.ok) {
      throw new ApiError(
        result.reason === 'not_found' ? ERROR_CODES.notFound : ERROR_CODES.conflict,
      )
    }

    await writeAudit({
      action: AUDIT_ACTIONS.connectorFaultInjected,
      entity: 'integration_connector',
      entityId: params.code,
      user,
      request,
      detail: body.faultKind || 'cleared',
    })

    return { ok: true, faultKind: body.faultKind ?? '' }
  },
)
