import { NextRequest, NextResponse } from 'next/server'
import { apiProviderRepo } from '@/lib/database/repositories/api-provider.repo'
import { isAuthError, requireUser } from '@/lib/auth/session'
import { getBuiltinApiProvider } from '@/lib/api-provider-catalog'

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  let user
  try {
    user = await requireUser()
  } catch (err) {
    if (isAuthError(err)) return err
    throw err
  }
  const { id } = await params

  let existing = apiProviderRepo.findByIdAndUser(id, user.id)
  if (!existing) {
    const builtin = getBuiltinApiProvider(id)
    if (!builtin) return NextResponse.json({ error: 'Provider not found' }, { status: 404 })
    apiProviderRepo.upsertBuiltin(id, builtin.name, user.id)
    existing = apiProviderRepo.findByIdAndUser(id, user.id)
    if (!existing) return NextResponse.json({ error: 'Provider not found' }, { status: 404 })
  }

  let body: Record<string, unknown>
  try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }

  const fields: { apiKey?: string; baseUrl?: string; isActive?: number; status?: string; statusError?: string; name?: string; modelName?: string } = {}
  if (typeof body.api_key === 'string') fields.apiKey = body.api_key
  if (typeof body.base_url === 'string') fields.baseUrl = body.base_url
  if (body.is_active !== undefined) fields.isActive = Number(body.is_active)
  if (typeof body.status === 'string') fields.status = body.status
  if (typeof body.status_error === 'string') fields.statusError = body.status_error
  if (typeof body.name === 'string') fields.name = body.name
  if (typeof body.model_name === 'string') fields.modelName = body.model_name

  // Auto-reset status when api_key changes
  if ('api_key' in body && !('status' in body)) {
    fields.status = 'not_configured'
    fields.statusError = ''
  }

  if (Object.keys(fields).length === 0) return NextResponse.json({ error: 'No valid fields' }, { status: 400 })

  apiProviderRepo.updateFields(id, user.id, fields)

  const updated = apiProviderRepo.findByIdAndUser(id, user.id)
  return NextResponse.json(updated)
}

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  let user
  try {
    user = await requireUser()
  } catch (err) {
    if (isAuthError(err)) return err
    throw err
  }
  const { id } = await params

  if (!id.startsWith('custom-')) {
    return NextResponse.json({ error: 'Only custom providers can be deleted' }, { status: 403 })
  }

  const existing = apiProviderRepo.findByIdAndUser(id, user.id)
  if (!existing) return NextResponse.json({ error: 'Provider not found' }, { status: 404 })

  apiProviderRepo.deleteByIdAndUser(id, user.id)
  return NextResponse.json({ success: true })
}
