import type { APIRoute } from 'astro';
import { supabase, supabaseAdmin } from '../../../../lib/supabase';
import { getTokenFromHeader, verifyToken } from '../../../../lib/auth';

export const GET: APIRoute = async ({ params, request }) => {
  try {
    const { id } = params;
    
    if (!id) {
      return new Response(JSON.stringify({ error: 'Order ID is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const authHeader = request.headers.get('authorization');
    const token = getTokenFromHeader(authHeader);
    const payload = verifyToken(token || '');
    
    const { data: order, error } = await supabase
      .from('orders')
      .select(`
        *,
        items:order_items(*, product:products(id, name, slug, images)),
        user:users(id, name, email)
      `)
      .eq('id', id)
      .single();
    
    if (error || !order) {
      return new Response(JSON.stringify({ error: 'Order not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    if (payload) {
      const isOwner = order.user_id === payload.userId;
      const isAdmin = payload.role === 'admin';
      
      if (!isOwner && !isAdmin) {
        return new Response(JSON.stringify({ error: 'Access denied' }), {
          status: 403,
          headers: { 'Content-Type': 'application/json' }
        });
      }
    }
    
    return new Response(JSON.stringify({
      success: true,
      order
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Get order error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

export const PATCH: APIRoute = async ({ params, request }) => {
  try {
    const { id } = params;
    
    if (!id) {
      return new Response(JSON.stringify({ error: 'Order ID is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const authHeader = request.headers.get('authorization');
    const token = getTokenFromHeader(authHeader);
    const payload = verifyToken(token || '');
    
    if (!payload) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const body = await request.json();
    const { status, notes } = body;
    
    const { data: order } = await supabase
      .from('orders')
      .select('id, user_id, status')
      .eq('id', id)
      .single();
    
    if (!order) {
      return new Response(JSON.stringify({ error: 'Order not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const updates: any = {};
    
    if (status && ['pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled'].includes(status)) {
      if (payload.role !== 'vendor' && payload.role !== 'admin') {
        if (status === 'cancelled' && order.user_id !== payload.userId) {
          return new Response(JSON.stringify({ error: 'Only order owner or admin can cancel' }), {
            status: 403,
            headers: { 'Content-Type': 'application/json' }
          });
        }
        if (status !== 'cancelled') {
          return new Response(JSON.stringify({ error: 'Only vendors can update order status' }), {
            status: 403,
            headers: { 'Content-Type': 'application/json' }
          });
        }
      }
      updates.status = status;
    }
    
    if (notes !== undefined) {
      updates.notes = notes;
    }
    
    const { data: updatedOrder, error } = await supabaseAdmin
      .from('orders')
      .update(updates)
      .eq('id', id)
      .select()
      .single();
    
    if (error) {
      throw error;
    }
    
    return new Response(JSON.stringify({
      success: true,
      order: updatedOrder
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Update order error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
