import {
  type BlueprintDocumentFunctionResourceEvent,
  type BlueprintError,
  type BlueprintFunctionBaseResourceEvent,
  type BlueprintMediaLibraryFunctionResourceEvent,
  type FunctionRuntimes,
  VALID_RUNTIMES,
  validateResource,
} from '../index.js'
import {isReference} from '../utils/validation.js'

type BaseFunctionEventKey = keyof BlueprintFunctionBaseResourceEvent
const BASE_EVENT_KEYS = new Set<BaseFunctionEventKey>(['on', 'filter', 'projection', 'includeDrafts'])
type DocumentFunctionEventKey = keyof BlueprintDocumentFunctionResourceEvent
const DOCUMENT_EVENT_KEYS = new Set<DocumentFunctionEventKey>(['includeAllVersions', 'resource', ...BASE_EVENT_KEYS.values()])
type MediaLibraryFunctionEventKey = keyof BlueprintMediaLibraryFunctionResourceEvent
const MEDIA_LIBRARY_EVENT_KEYS = new Set<MediaLibraryFunctionEventKey>(['resource', ...BASE_EVENT_KEYS.values()])

const MINUTES = /^(\*(\/([1-5]?\d))?|([0-5]?\d)(-[0-5]?\d)?(\/([1-5]?\d))?)(,(\*(\/([1-5]?\d))?|([0-5]?\d)(-[0-5]?\d)?(\/([1-5]?\d))?))*$/
const HOURS =
  /^(\*(\/([1-9]|1\d|2[0-3]))?|([01]?\d|2[0-3])(-([01]?\d|2[0-3]))?(\/([1-9]|1\d|2[0-3]))?)(,(\*(\/([1-9]|1\d|2[0-3]))?|([01]?\d|2[0-3])(-([01]?\d|2[0-3]))?(\/([1-9]|1\d|2[0-3]))?))*$/
const DAY_OF_MONTH =
  /^(\*(\/([1-9]|[12]\d|3[01]))?|([1-9]|[12]\d|3[01])(-([1-9]|[12]\d|3[01]))?(\/([1-9]|[12]\d|3[01]))?)(,(\*(\/([1-9]|[12]\d|3[01]))?|([1-9]|[12]\d|3[01])(-([1-9]|[12]\d|3[01]))?(\/([1-9]|[12]\d|3[01]))?))*$/
const MONTH =
  /^(\*(\/([1-9]|1[0-2]))?|([1-9]|1[0-2]|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-([1-9]|1[0-2]|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?(\/([1-9]|1[0-2]))?)(,(\*(\/([1-9]|1[0-2]))?|([1-9]|1[0-2]|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-([1-9]|1[0-2]|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?(\/([1-9]|1[0-2]))?))*$/i
const DAY_OF_WEEK =
  /^(\*(\/([0-7]))?|([0-7]|SUN|MON|TUE|WED|THU|FRI|SAT)(-([0-7]|SUN|MON|TUE|WED|THU|FRI|SAT))?(\/([0-7]))?)(,(\*(\/([0-7]))?|([0-7]|SUN|MON|TUE|WED|THU|FRI|SAT)(-([0-7]|SUN|MON|TUE|WED|THU|FRI|SAT))?(\/([0-7]))?))*$/i

/**
 * Validates a document function resource configuration.
 * Checks that the function has a valid event configuration, correct type, and all required base properties.
 * @param functionResource The function resource to validate
 * @category Functions Types
 * @returns Array of validation errors, empty if valid
 */
export function validateDocumentFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = validateFunction(functionResource)

  // event validation
  if ('event' in functionResource) {
    // `event` was specified, but event keys (aggregated in `maybeEvent`) were also specified at the top level. ambiguous and deprecated usage.
    const duplicateKeys = Array.from(DOCUMENT_EVENT_KEYS).filter((key) => key in functionResource)
    if (duplicateKeys.length > 0) {
      errors.push({
        type: 'invalid_property',
        message: `\`event\` properties should be specified under the \`event\` key - specifying them at the top level is deprecated. The following keys were specified at the top level: ${duplicateKeys.map((k) => `\`${k}\``).join(', ')}`,
      })
    } else {
      errors.push(...validateDocumentFunctionEvent(functionResource.event))
    }
  } else {
    errors.push(...validateDocumentFunctionEvent(functionResource))
  }

  if ('type' in functionResource && functionResource.type !== 'sanity.function.document') {
    errors.push({type: 'invalid_value', message: '`type` must be `sanity.function.document`'})
  }

  return errors
}

/**
 * Validates a media library asset function resource configuration.
 * Checks that the function has a valid event configuration with required resource, correct type, and all required base properties.
 * @param functionResource The function resource to validate
 * @category Functions Types
 * @returns Array of validation errors, empty if valid
 */
export function validateMediaLibraryAssetFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = validateFunction(functionResource)

  if ('event' in functionResource) {
    errors.push(...validateMediaLibraryFunctionEvent(functionResource.event))
  } else {
    errors.push({type: 'missing_parameter', message: '`event` is required for a media library function'})
  }

  if ('type' in functionResource && functionResource.type !== 'sanity.function.media-library.asset') {
    errors.push({type: 'invalid_value', message: '`type` must be `sanity.function.media-library.asset`'})
  }

  return errors
}

/**
 * Validates base function resource properties.
 * Checks that required fields (name, type) are present and that optional fields have correct types.
 * @param functionResource The function resource to validate
 * @internal
 * @returns Array of validation errors, empty if valid
 */
export function validateFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = validateResource(functionResource)

  if (!('name' in functionResource)) {
    errors.push({type: 'missing_parameter', message: '`name` is required'})
  } else if (typeof functionResource.name !== 'string') {
    errors.push({type: 'invalid_type', message: '`name` must be a string'})
  }

  if (!('type' in functionResource)) {
    errors.push({type: 'missing_parameter', message: '`type` is required'})
  } else if (typeof functionResource.type !== 'string') {
    errors.push({type: 'invalid_type', message: '`type` must be a string'})
  }

  // type validation
  if ('memory' in functionResource) {
    if (typeof functionResource.memory !== 'number' && typeof functionResource.memory !== 'undefined') {
      errors.push({type: 'invalid_type', message: '`memory` must be a number'})
    }
  }
  if ('timeout' in functionResource) {
    if (typeof functionResource.timeout !== 'number' && typeof functionResource.timeout !== 'undefined') {
      errors.push({type: 'invalid_type', message: '`timeout` must be a number'})
    }
  }

  if ('robotToken' in functionResource) {
    if (typeof functionResource.robotToken !== 'string' && typeof functionResource.robotToken !== 'undefined') {
      errors.push({type: 'invalid_type', message: '`robotToken` must be a string'})
    }
  }

  if ('runtime' in functionResource) {
    if (typeof functionResource.runtime !== 'undefined' && !VALID_RUNTIMES.includes(functionResource.runtime as FunctionRuntimes)) {
      errors.push({type: 'invalid_value', message: `\`runtime\` must be one of ${VALID_RUNTIMES.join(', ')}`})
    }
  }

  if ('env' in functionResource && typeof functionResource.env !== 'undefined') {
    if (typeof functionResource.env !== 'object' || functionResource.env === null) {
      errors.push({type: 'invalid_type', message: `\`env\` must be an object`})
    } else {
      for (const [key, value] of Object.entries(functionResource.env)) {
        if (typeof value !== 'string') {
          errors.push({type: 'invalid_type', message: `\`env[${key}]\` must be a string`})
        }
      }
    }
  }

  return errors
}

/**
 * Validates a document function event configuration.
 * Checks event trigger types, optional filter/projection, and optional dataset resource scoping.
 * @param event The event configuration to validate
 * @returns Array of validation errors, empty if valid
 */
function validateDocumentFunctionEvent(event: unknown): BlueprintError[] {
  if (!event) return [{type: 'invalid_value', message: 'Function event must be provided'}]
  if (typeof event !== 'object') return [{type: 'invalid_type', message: 'Function event must be an object'}]

  const cleanEvent = Object.fromEntries(
    Object.entries(event).filter(([key]) => DOCUMENT_EVENT_KEYS.has(key as DocumentFunctionEventKey)),
  ) as Partial<BlueprintDocumentFunctionResourceEvent>
  const errors: BlueprintError[] = []

  const fullEvent = {
    on: cleanEvent.on || ['publish'],
    ...cleanEvent,
  }
  if (!Array.isArray(fullEvent.on)) errors.push({type: 'invalid_type', message: '`event.on` must be an array'})
  if (fullEvent.resource) {
    errors.push(...validateFunctionEventResourceDataset(fullEvent))
  }
  return errors
}

function validateFunctionEventResourceDataset(event: unknown): BlueprintError[] {
  const errors: BlueprintError[] = []
  if (!event || typeof event !== 'object') return [{type: 'invalid_value', message: '`event` must be an object'}]
  // `resource` is optional for the event types that reach here (document and sync-tag-invalidate),
  // so there is nothing to validate when it is absent.
  if (!('resource' in event) || typeof event.resource === 'undefined') return []
  const resource = event.resource
  if (!resource || typeof resource !== 'object') return [{type: 'invalid_value', message: '`event.resource` must be an object'}]
  if (!('type' in resource) || !resource.type || resource.type !== 'dataset')
    errors.push({type: 'invalid_value', message: '`event.resource.type` must be "dataset"'})
  if (
    !('id' in resource) ||
    !resource.id ||
    typeof resource.id !== 'string' ||
    !(isReference(resource.id) || resource.id.split('.').length === 2)
  )
    errors.push({type: 'invalid_format', message: '`event.resource.id` must be in the format <projectId>.<datasetName>'})
  return errors
}
/**
 * Validates a media library function event configuration.
 * Checks event trigger types and ensures required media library resource is present.
 * @param event The event configuration to validate
 * @returns Array of validation errors, empty if valid
 */
function validateMediaLibraryFunctionEvent(event: unknown): BlueprintError[] {
  if (!event) return [{type: 'invalid_value', message: 'Function event must be provided'}]
  if (typeof event !== 'object') return [{type: 'invalid_type', message: 'Function event must be an object'}]

  const cleanEvent = Object.fromEntries(
    Object.entries(event).filter(([key]) => MEDIA_LIBRARY_EVENT_KEYS.has(key as MediaLibraryFunctionEventKey)),
  ) as BlueprintMediaLibraryFunctionResourceEvent
  const errors: BlueprintError[] = []

  const fullEvent = {
    on: cleanEvent.on || ['publish'],
    ...cleanEvent,
  }
  if (!Array.isArray(fullEvent.on)) errors.push({type: 'invalid_type', message: '`event.on` must be an array'})
  if (fullEvent.resource) {
    if (!fullEvent.resource.type || fullEvent.resource.type !== 'media-library')
      errors.push({type: 'invalid_value', message: '`event.resource.type` must be "media-library"'})
  } else {
    errors.push({type: 'missing_parameter', message: '`resource` is required for a media library function'})
  }
  return errors
}

/**
 * Validates a scheduled function resource configuration.
 * @hidden
 * @param functionResource The function resource to validate
 * @category Functions Types
 * @returns Array of validation errors, empty if valid
 */
export function validateScheduledFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = []

  if ('event' in functionResource) {
    errors.push(...validateScheduledFunctionEvent(functionResource.event))
  } else {
    errors.push({type: 'missing_parameter', message: '`event` is required for a scheduled function'})
  }

  if ('type' in functionResource && functionResource.type !== 'sanity.function.cron') {
    errors.push({type: 'invalid_value', message: '`type` must be `sanity.function.cron`'})
  }

  if ('timezone' in functionResource) {
    errors.push(...validateScheduledFunctionTimezone(functionResource.timezone))
  }

  errors.push(...validateFunction(functionResource))

  return errors
}

/**
 * Validates a scheduled function event configuration.
 * @param event The event configuration to validate
 * @returns Array of validation errors, empty if valid
 */
function validateScheduledFunctionEvent(event: unknown): BlueprintError[] {
  if (!event) return [{type: 'invalid_value', message: 'Function event must be provided'}]
  if (typeof event !== 'object') return [{type: 'invalid_type', message: 'Function event must be an object'}]

  const errors: BlueprintError[] = []

  const hasExpression = 'expression' in event

  if (hasExpression) {
    errors.push({
      type: 'invalid_property',
      message: 'Cannot specify `expression`. Use `defineScheduledFunction` to convert this to explicit fields',
    })
  }
  if (!('minute' in event)) {
    errors.push({
      type: 'missing_parameter',
      message: '`minute` must be provided',
    })
  } else if (typeof event.minute !== 'string') {
    errors.push({type: 'invalid_type', message: '`minute` must be a string'})
  } else if (!MINUTES.test(event.minute)) {
    errors.push({
      type: 'invalid_value',
      message: `Invalid minute field: "${event.minute}"

The minute field must be:
- A number from 0 to 59
- A range like 0-10
- A step value like */5
- A list like 0,15,30,45
`,
    })
  }
  if (!('hour' in event)) {
    errors.push({
      type: 'missing_parameter',
      message: '`hour` must be provided',
    })
  } else if (typeof event.hour !== 'string') {
    errors.push({type: 'invalid_type', message: '`hour` must be a string'})
  } else if (!HOURS.test(event.hour)) {
    errors.push({
      type: 'invalid_value',
      message: `Invalid hour field: "${event.hour}"

The hour field must be:
- A number from 0 to 23
- A range like 9-17
- A step value like */2
- A list like 0,6,12,18
`,
    })
  }
  if (!('dayOfMonth' in event)) {
    errors.push({
      type: 'missing_parameter',
      message: '`dayOfMonth` must be provided',
    })
  } else if (typeof event.dayOfMonth !== 'string') {
    errors.push({type: 'invalid_type', message: '`dayOfMonth` must be a string'})
  } else if (!DAY_OF_MONTH.test(event.dayOfMonth)) {
    errors.push({
      type: 'invalid_value',
      message: `Invalid dayOfMonth field: "${event.dayOfMonth}"

The day-of-month field must be:
- A number from 1 to 31
- A range like 1-15
- A step value like */2
- A list like 1,15,31
`,
    })
  }
  if (!('month' in event)) {
    errors.push({
      type: 'missing_parameter',
      message: '`month` must be provided',
    })
  } else if (typeof event.month !== 'string') {
    errors.push({type: 'invalid_type', message: '`month` must be a string'})
  } else if (!MONTH.test(event.month)) {
    errors.push({
      type: 'invalid_value',
      message: `Invalid month field: "${event.month}"

The month field must be:
- A number from 1 to 12
- A range like 1-6
- A step value like */2
- A list like 1,4,7,10
- A month name like JAN or OCT-DEC
`,
    })
  }
  if (!('dayOfWeek' in event)) {
    errors.push({
      type: 'missing_parameter',
      message: '`dayOfWeek` must be provided',
    })
  } else if (typeof event.dayOfWeek !== 'string') {
    errors.push({type: 'invalid_type', message: '`dayOfWeek` must be a string'})
  } else if (!DAY_OF_WEEK.test(event.dayOfWeek)) {
    errors.push({
      type: 'invalid_value',
      message: `Invalid dayOfWeek field: "${event.dayOfWeek}"

The day-of-week field must be:
- A number from 0 to 7
- Sunday can be specified using 0 or 7
- A range like MON-FRI
- A step value like */2
- A list like MON,WED,FRI
`,
    })
  }

  return errors
}

/**
 * Validates a scheduled function timezone configuration.
 * @param timezone The timezone to validate
 * @returns Array of validation errors, empty if valid
 */
function validateScheduledFunctionTimezone(timezone: unknown): BlueprintError[] {
  if (typeof timezone !== 'string') return [{type: 'invalid_type', message: 'Function timezone must be a string'}]

  const errors: BlueprintError[] = []

  try {
    Intl.DateTimeFormat(undefined, {timeZone: timezone})
  } catch {
    errors.push({
      type: 'invalid_value',
      message: '`timezone` must be a valid IANA timezone',
    })
  }

  return errors
}

/**
 * Validates a sync tag invalidate function resource configuration.
 * @param functionResource The function resource to validate
 * @hidden
 * @category Functions Types
 * @returns Array of validation errors, empty if valid
 */
export function validateSyncTagInvalidateFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = []

  if ('type' in functionResource && functionResource.type !== 'sanity.function.sync-tag-invalidate') {
    errors.push({type: 'invalid_value', message: '`type` must be `sanity.function.sync-tag-invalidate`'})
  }

  if ('event' in functionResource) {
    errors.push(...validateFunctionEventResourceDataset(functionResource.event))
  }

  errors.push(...validateFunction(functionResource))

  return errors
}

/**
 * Validates a queue function resource configuration.
 * @param functionResource The function resource to validate
 * @alpha
 * @hidden
 * @category Functions Types
 * @returns Array of validation errors, empty if valid
 */
export function validateQueueFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = []

  if ('type' in functionResource && functionResource.type !== 'sanity.function.queue') {
    errors.push({type: 'invalid_value', message: '`type` must be `sanity.function.queue`'})
  }

  if ('concurrency' in functionResource) {
    if (typeof functionResource.concurrency !== 'number') {
      errors.push({type: 'invalid_type', message: '`concurrency` must be a number'})
    } else if (functionResource.concurrency < 1) {
      errors.push({type: 'invalid_type', message: '`concurrency` must be at least 1'})
    } else if (functionResource.concurrency > 500) {
      errors.push({type: 'invalid_value', message: '`concurrency` must be less than 500'})
    }
  }
  if ('fifo' in functionResource && typeof functionResource.fifo !== 'boolean') {
    errors.push({type: 'invalid_type', message: '`fifo` must be a boolean'})
  }
  if ('dlq' in functionResource && typeof functionResource.dlq !== 'boolean') {
    errors.push({type: 'invalid_type', message: '`dlq` must be a boolean'})
  }

  if ('event' in functionResource && typeof functionResource.event !== 'undefined') {
    errors.push(...validateFunctionContentLakeEvent(functionResource.event))
  }

  errors.push(...validateFunction(functionResource))

  return errors
}

/**
 * Validates a function event configuration.
 * The event is a discriminated union keyed by `type`; validation is delegated to the
 * matching per-type event validator.
 * @param event The event configuration to validate
 * @returns Array of validation errors, empty if valid
 */
function validateFunctionContentLakeEvent(event: unknown): BlueprintError[] {
  if (!event || typeof event !== 'object') return [{type: 'invalid_type', message: '`event` must be an object'}]
  if (!('type' in event)) return [{type: 'missing_parameter', message: '`event.type` is required'}]

  switch (event.type) {
    case 'document':
      return validateDocumentFunctionEvent(event)
    case 'media-library':
      return validateMediaLibraryFunctionEvent(event)
    case 'sync-tag-invalidate':
      return validateFunctionEventResourceDataset(event)
    default:
      return [
        {
          type: 'invalid_value',
          message: '`event.type` must be either `document`, `sync-tag-invalidate`, or `media-library`',
        },
      ]
  }
}

/**
 * Validates an event function resource configuration.
 * @param functionResource The function resource to validate
 * @hidden
 * @category Functions Types
 * @returns Array of validation errors, empty if valid
 */

export function validatePubSubFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = []

  if ('type' in functionResource && functionResource.type !== 'sanity.function.pubsub') {
    errors.push({type: 'invalid_value', message: '`type` must be `sanity.function.pubsub`'})
  }

  errors.push(...validateFunction(functionResource))

  return errors
}

/**
 * Validates a durable function resource configuration.
 * @param functionResource The function resource to validate
 * @alpha
 * @hidden
 * @category Functions Types
 * @returns Array of validation errors, empty if valid
 */
export function validateDurableFunction(functionResource: unknown): BlueprintError[] {
  if (!functionResource) return [{type: 'invalid_value', message: 'Function config must be provided'}]
  if (typeof functionResource !== 'object') return [{type: 'invalid_type', message: 'Function config must be an object'}]

  const errors: BlueprintError[] = []

  if ('type' in functionResource && functionResource.type !== 'sanity.function.durable') {
    errors.push({type: 'invalid_value', message: '`type` must be `sanity.function.durable`'})
  }

  if ('debounceKey' in functionResource && typeof functionResource.debounceKey !== 'string') {
    errors.push({type: 'invalid_type', message: '`debounceKey` must be a string'})
  }

  if ('debounceKey' in functionResource && !('debounce' in functionResource)) {
    errors.push({type: 'invalid_value', message: '`debounceKey` requires a `debounce` to be set'})
  }

  if ('concurrency' in functionResource && typeof functionResource.concurrency !== 'number') {
    errors.push({type: 'invalid_type', message: '`concurrency` must be a number'})
  }

  if ('concurrency' in functionResource && typeof functionResource.concurrency === 'number' && functionResource.concurrency < 1) {
    errors.push({type: 'invalid_value', message: '`concurrency` must be at least 1'})
  }

  if ('concurrency' in functionResource && typeof functionResource.concurrency === 'number' && functionResource.concurrency > 500) {
    errors.push({type: 'invalid_value', message: '`concurrency` must be less than 500'})
  }

  if ('debounce' in functionResource && typeof functionResource.debounce !== 'number') {
    errors.push({type: 'invalid_type', message: '`debounce` must be a number'})
  }

  if ('durableTimeout' in functionResource && typeof functionResource.durableTimeout !== 'number') {
    errors.push({type: 'invalid_type', message: '`durableTimeout` must be a number'})
  }

  if ('durableTimeout' in functionResource && typeof functionResource.durableTimeout === 'number') {
    if (functionResource.durableTimeout < 60) {
      errors.push({type: 'invalid_value', message: '`durableTimeout` must be at least 60 seconds'})
    }
    if (functionResource.durableTimeout > 31_536_000) {
      errors.push({type: 'invalid_value', message: '`durableTimeout` must be at most a year'})
    }
  }

  if ('event' in functionResource) {
    errors.push(...validateFunctionContentLakeEvent(functionResource.event))
  }

  errors.push(...validateFunction(functionResource))

  return errors
}
