import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { connectorMappingSchema, type ConnectorMappingInput } from '@/lib/api/schemas'
import { deleteMapping, upsertMapping } from '@/lib/services/integration-service'

export const dynamic = 'force-dynamic'

/** Create or update one field mapping. */
export const POST = apiRoute<{ code: string }, ConnectorMappingInput>(
  { permission: 'integrations.map', bodySchema: connectorMappingSchema, limit: 40 },
  async ({ params, body, user, request }) => {
    const ok = await upsertMapping({ code: params.code, ...body })
    if (!ok) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.connectorMapped,
      entity: 'integration_connector',
      entityId: params.code,
      user,
      request,
      detail: `${body.sourceField} → ${body.targetField} (${body.sourceUnit || '—'} → ${body.targetUnit || '—'})`,
    })

    return { ok: true }
  },
)

/** Remove a mapping. The source field then stops reaching the platform at all. */
export const DELETE = apiRoute<{ code: string }>(
  { permission: 'integrations.map', limit: 40 },
  async ({ params, searchParams, user, request }) => {
    const sourceField = searchParams.get('sourceField')
    if (!sourceField) {
      throw new ApiError(ERROR_CODES.validationFailed, { details: { sourceField: 'required' } })
    }

    const ok = await deleteMapping(params.code, sourceField)
    if (!ok) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.connectorMapped,
      entity: 'integration_connector',
      entityId: params.code,
      user,
      request,
      detail: `removed ${sourceField}`,
    })

    return { ok: true }
  },
)
