import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '../composables/useApi'

export const useAuthStore = defineStore('auth', () => {
  const loggedIn = ref(false)

  function checkLogin() {
    const exp = localStorage.getItem('sp_login_expires')
    loggedIn.value = exp && Date.now() < parseInt(exp)
    return loggedIn.value
  }

  async function login(password) {
    const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(password))
    const hash = Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('')
    await api.post('/api/login', { hash })
    localStorage.setItem('sp_login_expires', String(Date.now() + 7 * 86400000))
    loggedIn.value = true
  }

  function logout() {
    localStorage.removeItem('sp_login_expires')
    loggedIn.value = false
  }

  async function changePassword(oldPass, newPass) {
    const hash = async (s) => {
      const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s))
      return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('')
    }
    await api.post('/api/change-password', {
      oldHash: await hash(oldPass),
      newHash: await hash(newPass),
    })
  }

  // Auto-check on init
  checkLogin()

  return { loggedIn, checkLogin, login, logout, changePassword }
})
