import { describe, it, expect, vi, beforeEach } from 'vitest'
import { POST } from './route'
import { NextRequest } from 'next/server'

// Mock prisma
vi.mock('@/lib/prisma', () => ({
  prisma: {
    user: {
      findUnique: vi.fn(),
      create: vi.fn(),
    },
  },
}))

// Mock bcryptjs
vi.mock('bcryptjs', () => ({
  default: {
    hash: vi.fn().mockResolvedValue('$2b$12$hashedpassword'),
    compare: vi.fn(),
  },
}))

import { prisma } from '@/lib/prisma'

function makeRequest(body: unknown) {
  return new NextRequest('http://localhost/api/auth/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

describe('POST /api/auth/register', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('returns 201 with valid data', async () => {
    vi.mocked(prisma.user.findUnique).mockResolvedValue(null)
    vi.mocked(prisma.user.create).mockResolvedValue({
      id: 'user-1',
      email: 'test@example.com',
      name: 'Test User',
    } as any)

    const res = await POST(makeRequest({ name: 'Test User', email: 'test@example.com', password: 'password123' }))
    expect(res.status).toBe(201)
    const data = await res.json()
    expect(data.user.email).toBe('test@example.com')
  })

  it('returns 422 with invalid email', async () => {
    const res = await POST(makeRequest({ name: 'Test', email: 'not-an-email', password: 'password123' }))
    expect(res.status).toBe(422)
  })

  it('returns 422 with short password', async () => {
    const res = await POST(makeRequest({ name: 'Test', email: 'test@example.com', password: 'short' }))
    expect(res.status).toBe(422)
  })

  it('returns 409 when email already exists', async () => {
    vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'existing' } as any)
    const res = await POST(makeRequest({ name: 'Test', email: 'test@example.com', password: 'password123' }))
    expect(res.status).toBe(409)
  })

  it('returns 400 for invalid JSON', async () => {
    const req = new NextRequest('http://localhost/api/auth/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: 'not json',
    })
    const res = await POST(req)
    expect(res.status).toBe(400)
  })
})
