import http from '@/api/http'

export interface QuickEntriesDto {
  keys: string[]
  usingDefaults: boolean
}

const MOCK_STORAGE_KEY = 'simple.mock.dashboard.quickEntries'

function mockStorageKey(scope: string, userId: string) {
  return `${MOCK_STORAGE_KEY}.${scope}.${userId}`
}

function isMock() {
  return import.meta.env.VITE_USE_MOCK === 'true'
}

function mockLoad(scope: string, userId: string): QuickEntriesDto | null {
  try {
    const raw = localStorage.getItem(mockStorageKey(scope, userId))
    return raw ? (JSON.parse(raw) as QuickEntriesDto) : null
  } catch {
    return null
  }
}

function mockSave(scope: string, userId: string, dto: QuickEntriesDto) {
  try {
    localStorage.setItem(mockStorageKey(scope, userId), JSON.stringify(dto))
  } catch { /* ignore */ }
}

export async function fetchQuickEntryKeys(userId: string, scope: string): Promise<QuickEntriesDto> {
  if (isMock()) {
    return mockLoad(scope, userId) ?? { keys: [], usingDefaults: true }
  }
  const { data } = await http.get<QuickEntriesDto>('/dashboard/quick-entries')
  return data
}

export async function saveQuickEntryKeys(
  userId: string, scope: string, keys: string[]
): Promise<QuickEntriesDto> {
  if (isMock()) {
    const dto: QuickEntriesDto = { keys, usingDefaults: false }
    mockSave(scope, userId, dto)
    return dto
  }
  const { data } = await http.put<QuickEntriesDto>('/dashboard/quick-entries', { keys })
  return data
}
