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

vi.mock('@/lib/spots', () => ({
  listApprovedSpots: vi.fn().mockResolvedValue({ spots: [], nextCursor: null }),
}))
vi.mock('next-auth', () => ({ getServerSession: vi.fn() }))
vi.mock('@/lib/auth', () => ({ authOptions: {} }))
vi.mock('@/lib/prisma', () => ({
  prisma: {
    spot: {
      create: vi.fn().mockResolvedValue({ id: 'new-spot', name: 'Test Spot', status: 'PENDING' }),
    },
  },
}))
vi.mock('isomorphic-dompurify', () => ({ default: { sanitize: (s: string) => s } }))

import { getServerSession } from 'next-auth'

describe('GET /api/spots', () => {
  it('returns 200 with spots list', async () => {
    const res = await GET(new NextRequest('http://localhost/api/spots'))
    expect(res.status).toBe(200)
    const data = await res.json()
    expect(data).toHaveProperty('spots')
  })

  it('returns 422 for invalid difficulty', async () => {
    const res = await GET(new NextRequest('http://localhost/api/spots?difficulty=INVALID'))
    expect(res.status).toBe(422)
  })
})

describe('POST /api/spots', () => {
  beforeEach(() => vi.clearAllMocks())

  it('returns 401 when not authenticated', async () => {
    vi.mocked(getServerSession).mockResolvedValue(null)
    const res = await POST(new NextRequest('http://localhost/api/spots', {
      method: 'POST',
      body: JSON.stringify({ name: 'Test', description: 'A long enough description here', lat: 38.7, lng: -9.1, difficulty: 'BEGINNER' }),
    }))
    expect(res.status).toBe(401)
  })

  it('returns 201 when authenticated with valid data', async () => {
    vi.mocked(getServerSession).mockResolvedValue({ user: { id: 'user-1', role: 'USER', email: 'test@test.com' } } as any)
    const res = await POST(new NextRequest('http://localhost/api/spots', {
      method: 'POST',
      body: JSON.stringify({
        name: 'Parque das Nações',
        description: 'Vista incrível sobre o Tejo, excelente para drones iniciantes',
        lat: 38.768,
        lng: -9.093,
        difficulty: 'BEGINNER',
      }),
    }))
    expect(res.status).toBe(201)
  })

  it('returns 422 for missing required fields', async () => {
    vi.mocked(getServerSession).mockResolvedValue({ user: { id: 'user-1', role: 'USER', email: 'test@test.com' } } as any)
    const res = await POST(new NextRequest('http://localhost/api/spots', {
      method: 'POST',
      body: JSON.stringify({ name: 'X' }),
    }))
    expect(res.status).toBe(422)
  })
})
