// Server-side deny paths of exportQafComparisonCopilotDocx (PR #346 review
// fix). Mirrors app/wertstrom/__tests__/qaf-actions.test.ts's mocking: the
// flag gate must reject BEFORE any DB access — createClient throws if reached.

import { describe, it, expect, vi, beforeEach } from 'vitest'

const VALID_UUID = '22222222-2222-4222-8222-222222222222'

let copilotExportsEnabled = false
const createClientMock = vi.fn(() => {
  throw new Error('createClient must not be called on a denied export')
})

vi.mock('@/config/profiles', () => ({
  getProfile: vi.fn(() => ({ features: { copilotExports: copilotExportsEnabled } })),
}))
vi.mock('@/lib/supabase/server', () => ({
  createClient: () => createClientMock(),
}))

import { exportQafComparisonCopilotDocx, exportQafComparisonCopilotMd } from '../copilot-export-actions'

describe('exportQafComparisonCopilotDocx — server-side deny paths', () => {
  beforeEach(() => {
    copilotExportsEnabled = false
    createClientMock.mockClear()
  })

  it('rejects with ok:false when the copilotExports flag is disabled — no DB access, no buffer', async () => {
    const res = await exportQafComparisonCopilotDocx(VALID_UUID, '19.07.2026')
    expect(res.ok).toBe(false)
    if (!res.ok) expect(res.error.length).toBeGreaterThan(0)
    expect(createClientMock).not.toHaveBeenCalled()
  })

  it('rejects an invalid comparison id before flag/DB', async () => {
    copilotExportsEnabled = true
    const res = await exportQafComparisonCopilotDocx('not-a-uuid', '19.07.2026')
    expect(res).toEqual({ ok: false, error: 'invalid comparison id' })
    expect(createClientMock).not.toHaveBeenCalled()
  })
})

describe('exportQafComparisonCopilotMd — server-side deny paths (Demo-067 E, KAR-984)', () => {
  beforeEach(() => {
    copilotExportsEnabled = false
    createClientMock.mockClear()
  })

  it('rejects with ok:false when the copilotExports flag is disabled — no DB access, no buffer', async () => {
    const res = await exportQafComparisonCopilotMd(VALID_UUID, '19.07.2026')
    expect(res.ok).toBe(false)
    if (!res.ok) expect(res.error.length).toBeGreaterThan(0)
    expect(createClientMock).not.toHaveBeenCalled()
  })

  it('rejects an invalid comparison id before flag/DB', async () => {
    copilotExportsEnabled = true
    const res = await exportQafComparisonCopilotMd('not-a-uuid', '19.07.2026')
    expect(res).toEqual({ ok: false, error: 'invalid comparison id' })
    expect(createClientMock).not.toHaveBeenCalled()
  })
})
