import { sdk } from '../sdk'
import { configFile } from '../file-models/config.json'

const { InputSpec, Value } = sdk

const inputSpec = InputSpec.of({
  podcastindex_api_key: Value.text({
    name: 'PodcastIndex API Key',
    description:
      'First of the two credentials shown on your PodcastIndex account page after free signup at api.podcastindex.org. Both Key AND Secret are required for Spotify link resolution — paste the SECRET in the field below. Apple Podcasts and Fountain links work without any PodcastIndex auth.',
    required: false,
    default: null,
    masked: true,
    minLength: 0,
    maxLength: 256,
  }),
  podcastindex_api_secret: Value.text({
    name: 'PodcastIndex API Secret',
    description:
      'Second of the two credentials shown on your PodcastIndex account page (right next to the API Key — sometimes labeled "API Secret" or "auth secret"). REQUIRED alongside the API Key for the Spotify lookup to work — leaving this blank is the most common reason Spotify URLs fail with "PodcastIndex unconfigured."',
    required: false,
    default: null,
    masked: true,
    minLength: 0,
    maxLength: 256,
  }),
})

export const setPodcastIndex = sdk.Action.withInput(
  'set-podcastindex',

  async ({ effects }) => ({
    name: 'Set PodcastIndex Credentials',
    description:
      'Configure PodcastIndex API credentials so Recaps can resolve Spotify episode links. Optional — Apple Podcasts links work without this. Sign up free at api.podcastindex.org.',
    warning: null,
    allowedStatuses: 'any',
    group: 'External Services',
    visibility: 'enabled',
  }),

  inputSpec,

  async ({ effects }) => {
    const config = await configFile.read().once()
    return {
      podcastindex_api_key: config?.podcastindex_api_key || undefined,
      podcastindex_api_secret: config?.podcastindex_api_secret || undefined,
    }
  },

  async ({ effects, input }) => {
    await configFile.merge(effects, {
      podcastindex_api_key: input.podcastindex_api_key || '',
      podcastindex_api_secret: input.podcastindex_api_secret || '',
    })
    return null
  },
)
