import { GET } from '../route'
import { prisma } from '@/lib/prisma'

jest.mock('@/lib/prisma', () => ({
  prisma: { download: { findUnique: jest.fn() } },
}))

const mockFindUnique = prisma.download.findUnique as jest.Mock

function req(uuid: string) {
  return new Request(`http://localhost/api/downloads/${uuid}`)
}

const baseDownload = {
  uuid: 'abc',
  status: 'DONE',
  format: 'mp4',
  quality: 'best',
  subtitles: false,
  fileName: 'video.mp4',
  fileSize: BigInt(1_048_576),
  errorMsg: null,
  submittedAt: new Date('2026-01-01'),
  completedAt: new Date('2026-01-01'),
}

describe('GET /api/downloads/[uuid]', () => {
  it('returns 404 when not found', async () => {
    mockFindUnique.mockResolvedValue(null)
    const res = await GET(req('missing'), { params: Promise.resolve({ uuid: 'missing' }) })
    expect(res.status).toBe(404)
  })

  it('returns 200 with download fields', async () => {
    mockFindUnique.mockResolvedValue({ ...baseDownload, tokens: [] })
    const res = await GET(req('abc'), { params: Promise.resolve({ uuid: 'abc' }) })
    expect(res.status).toBe(200)
    const body = await res.json()
    expect(body.uuid).toBe('abc')
    expect(body.fileSize).toBe('1048576')
  })

  it('returns downloadToken when status is DONE and token is valid', async () => {
    mockFindUnique.mockResolvedValue({
      ...baseDownload,
      tokens: [{ token: 'valid-tok', expiresAt: new Date(Date.now() + 3_600_000) }],
    })
    const res = await GET(req('abc'), { params: Promise.resolve({ uuid: 'abc' }) })
    const body = await res.json()
    expect(body.downloadToken).toBe('valid-tok')
  })

  it('returns null downloadToken when token is expired', async () => {
    mockFindUnique.mockResolvedValue({
      ...baseDownload,
      tokens: [{ token: 'expired-tok', expiresAt: new Date(Date.now() - 1000) }],
    })
    const res = await GET(req('abc'), { params: Promise.resolve({ uuid: 'abc' }) })
    const body = await res.json()
    expect(body.downloadToken).toBeNull()
  })
})
