import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { fetchOpenMeteo } from '@/lib/weather'
import { prisma } from '@/lib/prisma'

const querySchema = z.object({
  lat: z.string().transform((v) => parseFloat(v)).pipe(z.number().min(-90).max(90)),
  lng: z.string().transform((v) => parseFloat(v)).pipe(z.number().min(-180).max(180)),
})

export async function GET(req: NextRequest) {
  const { searchParams } = req.nextUrl
  const parsed = querySchema.safeParse({ lat: searchParams.get('lat'), lng: searchParams.get('lng') })
  if (!parsed.success) return NextResponse.json({ error: 'lat and lng required' }, { status: 400 })

  const { lat, lng } = parsed.data
  const cacheKey = `${lat.toFixed(4)},${lng.toFixed(4)}:openmeteo`

  const cached = await prisma.weatherCache.findUnique({ where: { cacheKey } })
  if (cached && cached.expiresAt > new Date()) return NextResponse.json(cached.data)

  try {
    const weather = await fetchOpenMeteo(lat, lng)
    const expiresAt = new Date(Date.now() + 30 * 60 * 1000)
    await prisma.weatherCache.upsert({
      where: { cacheKey },
      update: { data: weather as object, expiresAt, lat, lng },
      create: { cacheKey, lat, lng, data: weather as object, source: 'openmeteo', expiresAt },
    })
    return NextResponse.json(weather)
  } catch (err) {
    console.error('Weather fetch error:', err)
    return NextResponse.json({ error: 'Weather unavailable' }, { status: 502 })
  }
}
