/**
 * (happy path delegation, error propagation, contract on Request identity).
 */
const postRecaptchaVerify = jest.fn()

jest.mock('@/services/recaptcha/recaptcha.verify', () => ({
  postRecaptchaVerify: (...args: unknown[]) =>
    postRecaptchaVerify(...args),
}))

import { POST } from '../route'

describe('app/api/recaptcha/verify/route.ts — POST handler', () => {
  beforeEach(() => {
    postRecaptchaVerify.mockReset()
  })

  describe('delegation contract', () => {
    it('forwards the incoming Request to postRecaptchaVerify and returns its Response', async () => {
      const expected = { status: 200 } as unknown as Response
      postRecaptchaVerify.mockResolvedValue(expected)

      const req = { method: 'POST' } as unknown as Request

      const res = await POST(req)

      expect(postRecaptchaVerify).toHaveBeenCalledTimes(1)
      expect(postRecaptchaVerify.mock.calls[0][0]).toBe(req)
      expect(res).toBe(expected)
    })

    it.each([
      { status: 200, label: 'success' },
      { status: 400, label: 'client error' },
      { status: 503, label: 'upstream error' },
    ])(
      'returns service outcome unchanged ($label, status $status)',
      async ({ status }) => {
        const expected = { status } as unknown as Response
        postRecaptchaVerify.mockResolvedValue(expected)
        const req = { method: 'POST', url: '/api/recaptcha/verify' } as unknown as Request

        const res = await POST(req)

        expect(res).toBe(expected)
        expect(postRecaptchaVerify).toHaveBeenCalledWith(req)
      }
    )
  })

  describe('errors', () => {
    it('propagates rejection when postRecaptchaVerify fails', async () => {
      const err = new Error('service unavailable')
      postRecaptchaVerify.mockRejectedValue(err)
      const req = {} as unknown as Request

      await expect(POST(req)).rejects.toThrow('service unavailable')
      expect(postRecaptchaVerify).toHaveBeenCalledWith(req)
    })
  })
})
