import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '../lib/api.js'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const loading = ref(false)

  const isLoggedIn = computed(() => !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const isArtist = computed(() => user.value?.role === 'artist')
  const likedTrackIds = computed(() => new Set(user.value?.likedTracks || []))

  async function checkSession() {
    try {
      const { data } = await api.get('/auth/me')
      if (data.success) user.value = data.data.user
    } catch {
      user.value = null
    }
  }

  async function login(identifier, password) {
    loading.value = true
    try {
      const { data } = await api.post('/auth/login', { identifier, password })
      if (data.success) user.value = data.data.user
      return { success: true }
    } catch (err) {
      const msg = err.response?.data?.message || 'Login failed'
      return { success: false, message: msg }
    } finally {
      loading.value = false
    }
  }

  async function register(form) {
    loading.value = true
    try {
      const { data } = await api.post('/auth/register', form)
      if (data.success) user.value = data.data.user
      return { success: true }
    } catch (err) {
      const msg = err.response?.data?.message || 'Registration failed'
      return { success: false, message: msg }
    } finally {
      loading.value = false
    }
  }

  async function logout() {
    try {
      await api.post('/auth/logout')
    } finally {
      user.value = null
    }
  }

  async function updateProfile(formData) {
    loading.value = true
    try {
      const { data } = await api.put('/auth/profile', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      if (data.success) user.value = data.data
      return { success: true }
    } catch (err) {
      const msg = err.response?.data?.message || 'Update failed'
      return { success: false, message: msg }
    } finally {
      loading.value = false
    }
  }

  async function toggleLike(trackId) {
    const isLiked = likedTrackIds.value.has(trackId)
    try {
      if (isLiked) {
        await api.delete(`/tracks/${trackId}/like`)
        if (user.value) {
          user.value.likedTracks = user.value.likedTracks.filter((id) => id !== trackId)
        }
      } else {
        await api.post(`/tracks/${trackId}/like`)
        if (user.value) {
          user.value.likedTracks.push(trackId)
        }
      }
    } catch {
      // ignore
    }
  }

  return {
    user, loading, isLoggedIn, isAdmin, isArtist, likedTrackIds,
    checkSession, login, register, logout, updateProfile, toggleLike,
  }
})
