/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
  // Set basic settings
  let settings = app.settings()

  const appUrl = $os.getenv('POCKETBASE_URL') || 'http://127.0.0.1:8090'
  const appName = $os.getenv('APP_NAME') || 'PocketBase'

  const smtpHost = $os.getenv('SMTP_HOST') || 'mailpit'
  const smtpPort = Number($os.getenv('SMTP_PORT') || 1025)

  unmarshal({
    meta: {
      appName,
      appUrl
    },
    smtp: {
      enabled: true,
      host: smtpHost,
      port: smtpPort
    }
  }, settings)

  app.save(settings)

  // Enable auth methods
  const collection = app.findCollectionByNameOrId('_pb_users_auth_')

  const googleClientId = $os.getenv('AUTH_GOOGLE_CLIENT_ID')
  const googleClientSecret = $os.getenv('AUTH_GOOGLE_CLIENT_SECRET')

  const appleClientId = $os.getenv('AUTH_APPLE_CLIENT_ID')
  const appleClientSecret = $os.getenv('AUTH_APPLE_CLIENT_SECRET')

  const providers = []
  if (googleClientId?.length && googleClientSecret?.length) {
    providers.push({
      name: 'google',
      clientId: googleClientId,
      clientSecret: googleClientSecret
    })
  }
  if (appleClientId?.length && appleClientSecret?.length) {
    providers.push({
      name: 'apple',
      clientId: appleClientId,
      clientSecret: appleClientSecret
    })
  }

  unmarshal({
    oauth2: {
      enabled: true,
      providers
    },
    otp: {
      duration: 300,
      enabled: true,
      length: 6
    }
  }, collection)
  app.save(collection)

  // Create admin user if it doesn't exist
  const email = $os.getenv('SUPERUSER_EMAIL')
  const password = $os.getenv('SUPERUSER_PW')

  if (email?.length && password?.length) {
    const existingUser = app.findFirstRecordByData('_superusers', 'email', email)

    if (!existingUser) {
      let superusers = app.findCollectionByNameOrId('_superusers')
      let record = new Record(superusers)
      record.set('email', email)
      record.set('password', password)
      app.save(record)
    }
  }
}, (app) => {
  const collection = app.findCollectionByNameOrId('_pb_users_auth_')

  unmarshal({
    oauth2: {
      enabled: false
    },
    otp: {
      duration: 180,
      enabled: false,
      length: 8
    }
  }, collection)

  app.save(collection)
})
