import { api } from '@/utils/request'
import type {
  PaginatedData,
  OperationLogRecord,
  OperationLogFilters,
} from '@/types/api'

export type { OperationLogRecord }

interface UserLookup {
  id: number
  username: string
}

interface RoleLookup {
  id: number
  name: string
}

interface RouteGroupLookup {
  id: number
  name: string
}

export const useOperationLogStore = defineStore('operationLog', () => {
  const logs = ref<OperationLogRecord[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    per_page: 20,
    total: 0,
  })
  const filters = reactive<OperationLogFilters>({
    user_id: undefined,
    action: undefined,
    target_type: undefined,
    created_at_range: null,
  })

  const users = ref<UserLookup[]>([])
  const roles = ref<RoleLookup[]>([])
  const routeGroups = ref<RouteGroupLookup[]>([])

  const userMap = computed(
    () => new Map(users.value.map((u) => [Number(u.id), u.username])),
  )
  const roleMap = computed(
    () => new Map(roles.value.map((r) => [Number(r.id), r.name])),
  )
  const routeGroupMap = computed(
    () => new Map(routeGroups.value.map((rg) => [Number(rg.id), rg.name])),
  )

  async function loadLookups() {
    const [userData, roleData, rgData] = await Promise.allSettled([
      api.get<PaginatedData<UserLookup>>('/api/v1/users', { per_page: 200 }),
      api.get<PaginatedData<RoleLookup>>('/api/v1/roles', { per_page: 200 }),
      api.get<PaginatedData<RouteGroupLookup>>('/api/v1/route-groups', { per_page: 200 }),
    ])
    if (userData.status === 'fulfilled') users.value = userData.value.items
    if (roleData.status === 'fulfilled') roles.value = roleData.value.items
    if (rgData.status === 'fulfilled') routeGroups.value = rgData.value.items
  }

  async function fetchLogs() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<OperationLogRecord>>(
        '/api/v1/logs/operations',
        {
          page: pagination.page,
          per_page: pagination.per_page,
          user_id: filters.user_id || undefined,
          action: filters.action || undefined,
          target_type: filters.target_type || undefined,
          created_at_from: filters.created_at_range?.[0] || undefined,
          created_at_to: filters.created_at_range?.[1] || undefined,
        },
      )
      logs.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      logs.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取操作日志列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  function resetFilters() {
    filters.user_id = undefined
    filters.action = undefined
    filters.target_type = undefined
    filters.created_at_range = null
    pagination.page = 1
  }

  return {
    logs,
    loading,
    pagination,
    filters,
    users,
    userMap,
    roleMap,
    routeGroupMap,
    loadLookups,
    fetchLogs,
    resetFilters,
  }
})
