import { defineStore } from 'pinia'
import { ref } from 'vue'
import { roleService, type Role, type Permission, type RoleCreate, type RoleUpdate } from '@/services/role'

// Cache duration: 5 minutes
const CACHE_DURATION = 5 * 60 * 1000

export const useRolesStore = defineStore('roles', () => {
  const roles = ref<Role[] | null>(null)
  const permissions = ref<Permission[] | null>(null)
  const rolesLastFetched = ref<number>(0)
  const permissionsLastFetched = ref<number>(0)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  let rolesInFlight: Promise<Role[]> | null = null
  let permissionsInFlight: Promise<Permission[]> | null = null

  async function fetchRoles(force = false): Promise<Role[]> {
    const now = Date.now()
    if (!force && roles.value && now - rolesLastFetched.value < CACHE_DURATION) {
      return roles.value
    }
    if (rolesInFlight) return rolesInFlight

    isLoading.value = true
    error.value = null

    rolesInFlight = (async () => {
      try {
        const data = await roleService.getRoles()
        roles.value = data
        rolesLastFetched.value = Date.now()
        return data
      } catch (err: any) {
        error.value = err.response?.data?.detail || 'Failed to fetch roles'
        throw err
      } finally {
        isLoading.value = false
        rolesInFlight = null
      }
    })()

    return rolesInFlight
  }

  async function fetchPermissions(force = false): Promise<Permission[]> {
    const now = Date.now()
    if (!force && permissions.value && now - permissionsLastFetched.value < CACHE_DURATION) {
      return permissions.value
    }
    if (permissionsInFlight) return permissionsInFlight

    permissionsInFlight = (async () => {
      try {
        const data = await roleService.getPermissions()
        permissions.value = data
        permissionsLastFetched.value = Date.now()
        return data
      } catch (err: any) {
        error.value = err.response?.data?.detail || 'Failed to fetch permissions'
        throw err
      } finally {
        permissionsInFlight = null
      }
    })()

    return permissionsInFlight
  }

  async function createRole(data: RoleCreate): Promise<Role> {
    const role = await roleService.createRole(data)
    if (roles.value) roles.value = [...roles.value, role]
    return role
  }

  async function updateRole(roleId: number, data: RoleUpdate): Promise<Role> {
    const role = await roleService.updateRole(roleId, data)
    if (roles.value) roles.value = roles.value.map(r => r.id === roleId ? role : r)
    return role
  }

  async function deleteRole(roleId: number): Promise<void> {
    await roleService.deleteRole(roleId)
    if (roles.value) roles.value = roles.value.filter(r => r.id !== roleId)
  }

  return {
    roles,
    permissions,
    isLoading,
    error,
    fetchRoles,
    fetchPermissions,
    createRole,
    updateRole,
    deleteRole
  }
})
