import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useDbMaintenanceStore } from '../src/stores/dbMaintenance.js'

function stubFetch(handler) {
  globalThis.fetch = vi.fn(async (url, init) => {
    const { status, body } = handler(url, init)
    return {
      ok: status >= 200 && status < 300,
      status,
      statusText: String(status),
      text: async () => (body == null ? '' : JSON.stringify(body)),
    }
  })
}

describe('dbMaintenance store', () => {
  beforeEach(() => setActivePinia(createPinia()))
  afterEach(() => vi.restoreAllMocks())

  it('loadStats populates the bloat table', async () => {
    const s = useDbMaintenanceStore()
    stubFetch(() => ({
      status: 200,
      body: { tables: [{ table: 'image_record', live: 5, dead: 1, dead_pct: 16.7, last_vacuum: null }] },
    }))
    await s.loadStats()
    expect(s.tables).toHaveLength(1)
    expect(s.tables[0].table).toBe('image_record')
  })

  it('runVacuum POSTs the trigger endpoint', async () => {
    const s = useDbMaintenanceStore()
    const calls = []
    stubFetch((url, init) => {
      calls.push({ url, init })
      return { status: 202, body: { status: 'queued' } }
    })
    await s.runVacuum()
    const c = calls.at(-1)
    expect(c.url).toContain('/api/admin/maintenance/vacuum')
    expect(c.init.method).toBe('POST')
  })
})
