import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useApi } from '../composables/useApi.js'
import { useAsyncAction } from '../composables/useAsyncAction.js'

export const useCredentialsStore = defineStore('credentials', () => {
  const api = useApi()

  const byPlatform = ref(new Map())
  const extensionKey = ref(null)
  const { loading, error, run } = useAsyncAction()

  async function loadAll() {
    await run(async () => {
      const arr = await api.get('/api/credentials')
      const m = new Map()
      for (const c of arr) m.set(c.platform, c)
      byPlatform.value = m
    })
  }

  async function upload(platform, credential_type, data) {
    const rec = await api.post('/api/credentials', {
      body: { platform, credential_type, data },
    })
    // Reflect the returned record immediately — the previous .delete()
    // call left the card rendering "no credential" for the gap between
    // upload completion and the caller's follow-up loadAll(). Audit
    // 2026-06-02.
    byPlatform.value.set(platform, rec)
    return rec
  }

  async function remove(platform) {
    await api.delete(`/api/credentials/${platform}`)
    byPlatform.value.delete(platform)
  }

  // Runs gallery-dl --simulate against an enabled source for the
  // platform. Returns {valid: bool|null, reason, last_verified?}.
  async function verify(platform) {
    return await api.post(`/api/credentials/${platform}/verify`)
  }

  async function loadKey() {
    const body = await api.get('/api/settings/extension_api_key')
    extensionKey.value = body.key
  }

  async function rotateKey() {
    const body = await api.post('/api/settings/extension_api_key/rotate')
    extensionKey.value = body.key
  }

  return {
    byPlatform, extensionKey, loading, error,
    loadAll, upload, remove, verify, loadKey, rotateKey,
  }
})
