import 'dotenv/config'
import PocketBase from 'pocketbase'

const POCKETBASE_URL = process.env['POCKETBASE_URL'] ?? ''
const POCKETBASE_ADMIN_EMAIL = process.env['POCKETBASE_ADMIN_EMAIL'] ?? ''
const POCKETBASE_ADMIN_PASSWORD = process.env['POCKETBASE_ADMIN_PASSWORD'] ?? ''

if (!POCKETBASE_URL || !POCKETBASE_ADMIN_EMAIL || !POCKETBASE_ADMIN_PASSWORD) {
  console.error('Missing env vars')
  process.exit(1)
}

const AUTH_ANY = '@request.auth.id != ""'
const AUTH_ADMIN = '@request.auth.role = "admin"'
const AUTH_OWN = '@request.auth.id = user'

// [listRule, viewRule, createRule, updateRule, deleteRule]
const RULES: Record<string, [string, string, string, string, string]> = {
  source_documents:          [AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  themes:                    [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  topics:                    [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  micro_learnings:           [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  curriculum_versions:       [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  curriculum_weeks:          [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  employee_curriculum_state: [AUTH_ANY,    AUTH_ANY,    AUTH_ANY,    AUTH_OWN,    AUTH_ADMIN],
  session_completions:       [AUTH_ANY,    AUTH_ANY,    AUTH_ANY,    '',          ''],
  gamification_profiles:     [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  badges:                    [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  employee_badges:           [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
  milestone_cards:           [AUTH_ANY,    AUTH_ANY,    AUTH_ADMIN,  AUTH_ADMIN,  AUTH_ADMIN],
}

async function main() {
  const pb = new PocketBase(POCKETBASE_URL)
  await pb.admins.authWithPassword(POCKETBASE_ADMIN_EMAIL, POCKETBASE_ADMIN_PASSWORD)

  const collections = await pb.collections.getFullList()

  for (const col of collections) {
    const rules = RULES[col.name]
    if (!rules) continue

    const [listRule, viewRule, createRule, updateRule, deleteRule] = rules
    await pb.collections.update(col.id, {
      listRule,
      viewRule,
      createRule,
      updateRule,
      deleteRule,
    })
    console.log(`✓ ${col.name}`)
  }

  console.log('\nAccess rules applied.')
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})
