import type { APIRoute } from 'astro';
import { verifyAuth } from '../../../lib/auth';

export const GET: APIRoute = async ({ request, cookies }) => {
  try {
    // Verify authentication using the same method as dashboard
    const auth = await verifyAuth(cookies);
    
    if (!auth) {
      return new Response(JSON.stringify({ 
        error: 'Not authenticated' 
      }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Return user data and profile
    return new Response(JSON.stringify({
      user: auth.user,
      profile: {
        organization_id: auth.organizationId,
        role: auth.user.user_metadata?.role || (auth.isAdmin ? 'admin' : 'user')
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('User API error:', error);
    return new Response(JSON.stringify({ 
      error: 'Internal server error' 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};