import { createClient } from '@supabase/supabase-js'; export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ message: 'Method not allowed' }); } const { code } = req.body; try { // Exchange GitHub code for access token const response = await fetch('https://github.com/login/oauth/access_token', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ client_id: process.env.GITHUB_CLIENT_ID, client_secret: process.env.GITHUB_CLIENT_SECRET, code, redirect_uri: process.env.GITHUB_REDIRECT_URI }) }); const data = await response.json(); if (data.error) { throw new Error(data.error_description || 'GitHub authentication failed'); } // Store the token in Supabase (optional) const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY); await supabase .from('user_tokens') .upsert({ user_id: req.session.user.id, // You'd need session management github_token: data.access_token, updated_at: new Date().toISOString() }); res.status(200).json({ access_token: data.access_token, token_type: data.token_type, scope: data.scope }); } catch (error) { console.error('GitHub auth error:', error); res.status(500).json({ message: error.message }); } }