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

vi.mock('@/lib/prisma', () => ({
  prisma: {
    claudeJob: { deleteMany: vi.fn() },
  },
}))

import { prisma } from '@/lib/prisma'
import { POST } from '@/app/api/cron/cleanup-agent-artifacts/route'

const mockPrisma = prisma as unknown as {
  claudeJob: { deleteMany: ReturnType<typeof vi.fn> }
}

const SECRET = 'test-cron-secret-abc123'

function makeReq(headers: Record<string, string> = {}): Request {
  return new Request('http://localhost:3000/api/cron/cleanup-agent-artifacts', {
    method: 'POST',
    headers,
  })
}

beforeEach(() => {
  vi.clearAllMocks()
  process.env.CRON_SECRET = SECRET
  mockPrisma.claudeJob.deleteMany.mockResolvedValue({ count: 0 })
})

describe('POST /api/cron/cleanup-agent-artifacts', () => {
  it('401 zonder Authorization-header', async () => {
    const res = await POST(makeReq())
    expect(res.status).toBe(401)
    expect(mockPrisma.claudeJob.deleteMany).not.toHaveBeenCalled()
  })

  it('401 met verkeerde secret', async () => {
    const res = await POST(makeReq({ authorization: 'Bearer wrong-secret' }))
    expect(res.status).toBe(401)
    expect(mockPrisma.claudeJob.deleteMany).not.toHaveBeenCalled()
  })

  it('200 met juiste secret + deleteMany aangeroepen voor FAILED/CANCELLED/SKIPPED ouder dan 7 dagen', async () => {
    mockPrisma.claudeJob.deleteMany.mockResolvedValue({ count: 5 })

    const res = await POST(makeReq({ authorization: 'Bearer ' + SECRET }))
    expect(res.status).toBe(200)
    const body = await res.json()
    expect(body.deleted).toBe(5)
    expect(body.ran_at).toMatch(/^\d{4}-\d{2}-\d{2}T/)

    const arg = mockPrisma.claudeJob.deleteMany.mock.calls[0][0]
    expect(arg.where.status).toEqual({ in: ['FAILED', 'CANCELLED', 'SKIPPED'] })
    expect(arg.where.finished_at.lt).toBeInstanceOf(Date)

    // cutoff should be approximately 7 days ago
    const cutoff = arg.where.finished_at.lt as Date
    const diffMs = Date.now() - cutoff.getTime()
    const diffDays = diffMs / (1000 * 60 * 60 * 24)
    expect(diffDays).toBeCloseTo(7, 0)
  })
})
