// @vitest-environment node
import { afterEach, describe, expect, it, vi } from 'vitest'

const cmsApi = vi.fn()
vi.mock('../../lib/api.js', () => ({
  cmsApi: (...args: unknown[]) => cmsApi(...args),
}))

const {
  fetchSeoOverview,
  fetchSeoContentRecords,
  fetchSeoIssues,
  fetchRedirectRules,
  updateSeoFields,
} = await import('../../lib/seo-service.js')

afterEach(() => {
  cmsApi.mockReset()
})

/**
 * Regression tests for the "swallowed read errors" blocker. `cmsApi` never
 * throws — it returns `{ error }` on failure — so the SEO read fetchers must
 * re-throw, otherwise `useSeoResource` can't distinguish "request failed" from
 * "empty result" and renders a misleading fallback (e.g. a fake score of 0 /
 * grade "Critical") with the error/retry UI permanently unreachable.
 */
describe('SEO service read fetchers surface errors', () => {
  it('fetchSeoOverview throws when the request fails (instead of returning a fake 0 score)', async () => {
    cmsApi.mockResolvedValue({ error: 'Request failed (500)', status: 500 })
    await expect(fetchSeoOverview()).rejects.toThrow('Request failed (500)')
  })

  it('fetchSeoContentRecords throws on error', async () => {
    cmsApi.mockResolvedValue({ error: 'Network error', status: 0 })
    await expect(fetchSeoContentRecords()).rejects.toThrow('Network error')
  })

  it('fetchSeoIssues throws on error', async () => {
    cmsApi.mockResolvedValue({ error: 'Request failed (503)', status: 503 })
    await expect(fetchSeoIssues()).rejects.toThrow('Request failed (503)')
  })

  it('fetchRedirectRules throws on error', async () => {
    cmsApi.mockResolvedValue({ error: 'boom', status: 500 })
    await expect(fetchRedirectRules()).rejects.toThrow('boom')
  })

  it('returns data normally on success', async () => {
    cmsApi.mockResolvedValue({ data: { records: [{ id: 'r1' }] }, status: 200 })
    await expect(fetchSeoContentRecords()).resolves.toEqual([{ id: 'r1' }])
  })

  it('mutations still return { error } rather than throwing', async () => {
    cmsApi.mockResolvedValue({ error: 'forbidden', status: 403 })
    await expect(updateSeoFields('page', 'doc-1', { metaTitle: 'x' })).resolves.toEqual({
      error: 'forbidden',
    })
  })
})
