import { describe, it, expect, vi, beforeEach } from 'vitest' import { NextRequest } from 'next/server' const mockSyncTariffs = vi.fn() vi.mock('@/lib/syncTariffs', () => ({ syncTariffs: mockSyncTariffs })) const CRON_SECRET = 'test-cron-secret' // matches vitest.setup.ts function makeRequest(token?: string): NextRequest { return new NextRequest('http://localhost/api/cron/tariffs', { method: 'GET', headers: token !== undefined ? { authorization: `Bearer ${token}` } : {}, }) } let GET: (req: NextRequest) => Promise beforeEach(async () => { vi.resetModules() mockSyncTariffs.mockReset() vi.stubEnv('CRON_SECRET', CRON_SECRET) const mod = await import('@/app/api/cron/tariffs/route') GET = mod.GET }) describe('GET /api/cron/tariffs', () => { it('returns 401 when authorization header is missing', async () => { const res = await GET(makeRequest()) expect(res.status).toBe(401) }) it('returns 401 for a wrong token', async () => { const res = await GET(makeRequest('wrong-token')) expect(res.status).toBe(401) }) it('returns 401 when CRON_SECRET is empty (no bypass allowed)', async () => { vi.stubEnv('CRON_SECRET', '') vi.resetModules() const mod = await import('@/app/api/cron/tariffs/route') const res = await mod.GET(makeRequest('')) expect(res.status).toBe(401) }) it('returns ok:true with sync counts on success', async () => { mockSyncTariffs.mockResolvedValueOnce({ synced: 3, created: 1, hidden: 0 }) const res = await GET(makeRequest(CRON_SECRET)) expect(res.status).toBe(200) const json = await res.json() expect(json.ok).toBe(true) expect(json.synced).toBe(3) expect(json.created).toBe(1) expect(json.hidden).toBe(0) }) it('returns 500 when syncTariffs throws', async () => { mockSyncTariffs.mockRejectedValueOnce(new Error('sync error')) const res = await GET(makeRequest(CRON_SECRET)) expect(res.status).toBe(500) expect((await res.json()).error).toBe('Sync failed') }) })