import { jsonResponse, errorResponse } from '../utils/cors'

// WebMCP server URL (localhost since they run on same machine)
const WEBMCP_URL = 'http://localhost:4102'

// WebMCP token storage (in-memory)
let pendingWebMCPToken: { token: string; createdAt: Date } | null = null

// Request token directly from WebMCP server
export async function handleWebMCPRequestToken(req: Request) {
  if (req.method !== 'POST') {
    return errorResponse('Method not allowed', 405)
  }

  try {
    const res = await fetch(`${WEBMCP_URL}/token`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    })

    if (!res.ok) {
      console.error('[WebMCP] Failed to request token from server:', res.status)
      return errorResponse('Failed to request token', res.status)
    }

    const data = await res.json()
    if (data.success && data.token) {
      console.log('[WebMCP] Token obtained from server')
      return jsonResponse({ success: true, token: data.token })
    }

    return errorResponse('Invalid response from WebMCP', 500)
  } catch (e) {
    console.error('[WebMCP] Error requesting token:', e)
    return errorResponse('WebMCP server not available', 503)
  }
}

export async function handleWebMCPToken(req: Request) {
  if (req.method === 'GET') {
    if (pendingWebMCPToken) {
      // Check if token is not expired (5 minutes)
      const age = Date.now() - pendingWebMCPToken.createdAt.getTime()
      if (age < 5 * 60 * 1000) {
        return jsonResponse({
          token: pendingWebMCPToken.token,
          createdAt: pendingWebMCPToken.createdAt.toISOString()
        })
      }
      // Token expired
      pendingWebMCPToken = null
    }
    return jsonResponse({ token: null })
  }

  if (req.method === 'POST') {
    const body = await req.json()
    if (body.token) {
      pendingWebMCPToken = {
        token: body.token,
        createdAt: new Date()
      }
      console.log('[WebMCP] Token received and stored')
      return jsonResponse({ success: true })
    }
    return errorResponse('Token required', 400)
  }

  if (req.method === 'DELETE') {
    pendingWebMCPToken = null
    return jsonResponse({ success: true })
  }

  return null
}
