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

export const POST: APIRoute = async ({ request }) => {
  try {
    // Verify admin authentication
    const auth = await requireAdmin(request);
    
    const { email } = await request.json();
    
    if (!email) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Email is required'
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if user exists
    const { data: existingUser } = await supabase
      .from('users')
      .select('id, email, role')
      .eq('email', email)
      .single();

    if (!existingUser) {
      return new Response(JSON.stringify({
        success: false,
        error: 'User not found. User must be registered first.'
      }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Make user admin using the database function
    const { error } = await supabase.rpc('make_user_admin', {
      user_email: email
    });

    if (error) {

      return new Response(JSON.stringify({
        success: false,
        error: 'Failed to make user admin'
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    return new Response(JSON.stringify({
      success: true,
      message: `Successfully made ${email} an admin`,
      user: {
        id: existingUser.id,
        email: existingUser.email,
        role: 'admin'
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {

    return new Response(JSON.stringify({
      success: false,
      error: 'Access denied or server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};