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

const { InputSpec, Value } = sdk

const inputSpec = InputSpec.of({
  recap_license_key: Value.text({
    name: 'Recaps License Key',
    description:
      'Paste your Recaps license key here. Keys start with "LIC1-..." — get one from your Recaps seller. (Keys are also accepted via the web UI activation screen.)',
    required: true,
    default: null,
    masked: true,
    minLength: 1,
    maxLength: 1024,
    patterns: [
      {
        regex: '^LIC1-.+',
        description: 'License keys start with "LIC1-".',
      },
    ],
  }),
})

export const setLicense = sdk.Action.withInput(
  'set-license',

  async ({ effects }) => ({
    name: 'Set Recaps License',
    description:
      'Activate a Recaps license to unlock paid features (channel & podcast subscriptions, auto-queue, and a monthly allotment of relay credits).',
    warning: null,
    allowedStatuses: 'any',
    group: 'Setup',
    visibility: 'enabled',
  }),

  inputSpec,

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

  async ({ effects, input }) => {
    const trimmed = (input.recap_license_key || '').trim()
    await configFile.merge(effects, { recap_license_key: trimmed })
    return null
  },
)
