import { NextRequest, NextResponse } from 'next/server'

const API = process.env.LEGAL_SERVICE_URL ?? 'http://localhost:3200'

export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const res = await fetch(`${API}/email/${id}`, { cache: 'no-store' })
  return NextResponse.json(await res.json(), { status: res.status })
}

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const url = new URL(req.url)
  const action = url.searchParams.get('action') // 'read' | 'archive' | 'associate'
  const endpoint = action
    ? `${API}/email/${id}/${action}`
    : `${API}/email/${id}`

  const body = await req.json().catch(() => ({}))
  const res = await fetch(endpoint, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  return NextResponse.json(await res.json(), { status: res.status })
}
