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

vi.mock('next-auth', () => ({ getServerSession: vi.fn() }))
vi.mock('@/lib/auth', () => ({ authOptions: {} }))
vi.mock('@/lib/prisma', () => ({
  prisma: {
    review: { update: vi.fn().mockResolvedValue({ id: 'r1', status: 'APPROVED', spotId: 's1' }) },
    moderationLog: { create: vi.fn().mockResolvedValue({}) },
  },
}))

import { getServerSession } from 'next-auth'

const req = (body: unknown) =>
  new NextRequest('http://localhost/api/reviews/r1/moderate', { method: 'PATCH', body: JSON.stringify(body) })

describe('PATCH /api/reviews/[id]/moderate', () => {
  beforeEach(() => vi.clearAllMocks())

  it('returns 401 unauthenticated', async () => {
    vi.mocked(getServerSession).mockResolvedValue(null)
    expect((await PATCH(req({ action: 'APPROVED' }), { params: { id: 'r1' } })).status).toBe(401)
  })

  it('returns 403 for USER', async () => {
    vi.mocked(getServerSession).mockResolvedValue({ user: { id: 'u1', role: 'USER', email: 'x@x.com' } } as any)
    expect((await PATCH(req({ action: 'APPROVED' }), { params: { id: 'r1' } })).status).toBe(403)
  })

  it('returns 200 for MODERATOR', async () => {
    vi.mocked(getServerSession).mockResolvedValue({ user: { id: 'm1', role: 'MODERATOR', email: 'm@x.com' } } as any)
    expect((await PATCH(req({ action: 'APPROVED' }), { params: { id: 'r1' } })).status).toBe(200)
  })

  it('returns 200 for ADMIN', async () => {
    vi.mocked(getServerSession).mockResolvedValue({ user: { id: 'a1', role: 'ADMIN', email: 'a@x.com' } } as any)
    expect((await PATCH(req({ action: 'REJECTED', note: 'Spam' }), { params: { id: 'r1' } })).status).toBe(200)
  })
})
