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