// getCalculatorParams mode-guard tests (KAR-960 review fix, PR #327 finding
// 3): before this fix, the DB-level `.eq('comparison_mode', 'g60')` guard on
// the qaf_comparison query had been REMOVED and replaced with only a comment
// claiming "kalkulator/page.tsx never offers this route for those modes" —
// a UI-only guarantee, not something the server action itself enforced. A
// 'multi_qaf'/'multi_qaf_variant_vs_standard' comparisonId used to fall
// through into the Summary-mode bridge branch and return real-looking (but
// semantically invalid) ALT/NEU calculator params.
//
// Strategy: mock @/lib/supabase/server (same pattern as
// app/api/v1/oee/__tests__/route.test.ts) so the action never touches a real
// DB — the mock's `from()` throws on any table beyond `qaf_comparison` for
// the guard-rejection cases, proving the guard returns BEFORE querying
// qaf_manufacturing_step/qaf_g60_tab/qaf_file for the modes it should reject.

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

const VALID_UUID = '11111111-1111-4111-8111-111111111111'

function makeSupabaseMock(opts: { comparisonMode: string | null; authenticated?: boolean }) {
  const authenticated = opts.authenticated ?? true
  const fromCalls: string[] = []

  const comparisonRow = {
    id: VALID_UUID,
    baseline_file_id: 'file-alt',
    comparison_file_id: 'file-neu',
    comparison_mode: opts.comparisonMode,
  }

  const supabase = {
    auth: {
      getClaims: vi.fn(() =>
        Promise.resolve(authenticated ? { data: { claims: { sub: 'user-1' } }, error: null } : { data: null, error: null }),
      ),
    },
    from: vi.fn((table: string) => {
      fromCalls.push(table)
      if (table === 'qaf_comparison') {
        return {
          select: vi.fn(() => ({
            eq: vi.fn(() => ({
              maybeSingle: vi.fn(() => Promise.resolve({ data: comparisonRow, error: null })),
            })),
          })),
        }
      }
      if (table === 'qaf_g60_tab') {
        return { select: vi.fn(() => ({ in: vi.fn(() => ({ eq: vi.fn(() => Promise.resolve({ data: [], error: null })) })) })) }
      }
      if (table === 'qaf_manufacturing_step') {
        return { select: vi.fn(() => ({ in: vi.fn(() => Promise.resolve({ data: [], error: null })) })) }
      }
      if (table === 'qaf_file') {
        return { select: vi.fn(() => ({ in: vi.fn(() => Promise.resolve({ data: [], error: null })) })) }
      }
      throw new Error(`unexpected table queried: ${table}`)
    }),
    _fromCalls: fromCalls,
  }
  return supabase
}

let currentMock = makeSupabaseMock({ comparisonMode: 'g60' })

vi.mock('@/lib/supabase/server', () => ({
  createClient: vi.fn(() => Promise.resolve(currentMock)),
}))

beforeEach(() => {
  vi.clearAllMocks()
})

async function loadAction() {
  const mod = await import('../comparison-meta-actions')
  return mod.getCalculatorParams
}

describe('getCalculatorParams mode guard (KAR-960 review fix, finding 3)', () => {
  it('rejects a multi_qaf comparison with ok:false — never queries manufacturing-step/g60-tab tables', async () => {
    currentMock = makeSupabaseMock({ comparisonMode: 'multi_qaf' })
    const getCalculatorParams = await loadAction()
    const res = await getCalculatorParams(VALID_UUID, '10')
    expect(res.ok).toBe(false)
    expect(currentMock._fromCalls).toEqual(['qaf_comparison'])
  })

  it('rejects a multi_qaf_variant_vs_standard comparison with ok:false — never queries manufacturing-step/g60-tab tables', async () => {
    currentMock = makeSupabaseMock({ comparisonMode: 'multi_qaf_variant_vs_standard' })
    const getCalculatorParams = await loadAction()
    const res = await getCalculatorParams(VALID_UUID, '10')
    expect(res.ok).toBe(false)
    expect(currentMock._fromCalls).toEqual(['qaf_comparison'])
  })

  it('still allows the g60 branch through (unchanged behavior)', async () => {
    currentMock = makeSupabaseMock({ comparisonMode: 'g60' })
    const getCalculatorParams = await loadAction()
    const res = await getCalculatorParams(VALID_UUID, 'Tab1')
    expect(res.ok).toBe(true)
    expect(currentMock._fromCalls).toContain('qaf_g60_tab')
  })

  it('still allows the summary bridge through for the explicit "summary" literal', async () => {
    currentMock = makeSupabaseMock({ comparisonMode: 'summary' })
    const getCalculatorParams = await loadAction()
    const res = await getCalculatorParams(VALID_UUID, '10')
    expect(res.ok).toBe(true)
    expect(currentMock._fromCalls).toContain('qaf_manufacturing_step')
  })

  it('still allows the summary bridge through for the legacy null comparison_mode', async () => {
    currentMock = makeSupabaseMock({ comparisonMode: null })
    const getCalculatorParams = await loadAction()
    const res = await getCalculatorParams(VALID_UUID, '10')
    expect(res.ok).toBe(true)
    expect(currentMock._fromCalls).toContain('qaf_manufacturing_step')
  })
})
