import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

interface CouponOperation {
  operation: 'create' | 'query' | 'update' | 'delete' | 'get';
  params?: Record<string, any>;
}

serve(async (req) => {
  // Handle CORS preflight requests
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const supabaseUrl = Deno.env.get('SUPABASE_URL');
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');

    if (!supabaseUrl || !supabaseServiceKey) {
      throw new Error('Missing Supabase configuration');
    }

    const supabase = createClient(supabaseUrl, supabaseServiceKey);

    // Verify JWT token
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) {
      return new Response(
        JSON.stringify({ error: 'Missing authorization header' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const token = authHeader.replace('Bearer ', '');
    const { data: { user }, error: authError } = await supabase.auth.getUser(token);

    if (authError || !user) {
      return new Response(
        JSON.stringify({ error: 'Unauthorized' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Check if user is admin
    const { data: profile } = await supabase
      .from('profiles')
      .select('role')
      .eq('user_id', user.id)
      .single();

    if (!profile || profile.role !== 'admin') {
      return new Response(
        JSON.stringify({ error: 'Forbidden: Admin access required' }),
        { status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const requestData: CouponOperation = await req.json();
    const { operation, params = {} } = requestData;

    console.log('Coupon operation:', operation, 'params:', params);

    let result;

    switch (operation) {
      case 'create': {
        // Create a new coupon
        const {
          name,
          code,
          type,
          discount_value,
          start_date,
          end_date,
          total_quantity,
          description,
          scope = 'all',
          scope_ids,
          min_purchase_amount = 0,
          max_discount_amount,
          per_user_limit = 1,
          status = 'active'
        } = params;

        if (!name || !code || !type || !discount_value || !start_date || !end_date || !total_quantity) {
          return new Response(
            JSON.stringify({ error: 'Missing required fields: name, code, type, discount_value, start_date, end_date, total_quantity' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const { data, error } = await supabase
          .from('coupons')
          .insert({
            name,
            code: code.toUpperCase(),
            type,
            discount_value,
            start_date,
            end_date,
            total_quantity,
            description,
            scope,
            scope_ids,
            min_purchase_amount,
            max_discount_amount,
            per_user_limit,
            status
          })
          .select()
          .single();

        if (error) {
          console.error('Create coupon error:', error);
          throw error;
        }

        result = { success: true, data };
        break;
      }

      case 'query': {
        // Query coupons with filters
        const { 
          status, 
          type, 
          scope,
          search,
          limit = 50,
          offset = 0 
        } = params;

        let query = supabase
          .from('coupons')
          .select('*', { count: 'exact' });

        if (status) {
          query = query.eq('status', status);
        }

        if (type) {
          query = query.eq('type', type);
        }

        if (scope) {
          query = query.eq('scope', scope);
        }

        if (search) {
          query = query.or(`name.ilike.%${search}%,code.ilike.%${search}%`);
        }

        query = query
          .order('created_at', { ascending: false })
          .range(offset, offset + limit - 1);

        const { data, error, count } = await query;

        if (error) {
          console.error('Query coupons error:', error);
          throw error;
        }

        result = { success: true, data, count };
        break;
      }

      case 'get': {
        // Get a single coupon by ID or code
        const { id, code } = params;

        if (!id && !code) {
          return new Response(
            JSON.stringify({ error: 'Missing required field: id or code' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        let query = supabase.from('coupons').select('*');

        if (id) {
          query = query.eq('id', id);
        } else {
          query = query.eq('code', code.toUpperCase());
        }

        const { data, error } = await query.single();

        if (error) {
          console.error('Get coupon error:', error);
          throw error;
        }

        result = { success: true, data };
        break;
      }

      case 'update': {
        // Update an existing coupon
        const { id, ...updateFields } = params;

        if (!id) {
          return new Response(
            JSON.stringify({ error: 'Missing required field: id' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        // If code is being updated, convert to uppercase
        if (updateFields.code) {
          updateFields.code = updateFields.code.toUpperCase();
        }

        const { data, error } = await supabase
          .from('coupons')
          .update(updateFields)
          .eq('id', id)
          .select()
          .single();

        if (error) {
          console.error('Update coupon error:', error);
          throw error;
        }

        result = { success: true, data };
        break;
      }

      case 'delete': {
        // Delete a coupon
        const { id } = params;

        if (!id) {
          return new Response(
            JSON.stringify({ error: 'Missing required field: id' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const { error } = await supabase
          .from('coupons')
          .delete()
          .eq('id', id);

        if (error) {
          console.error('Delete coupon error:', error);
          throw error;
        }

        result = { success: true, message: 'Coupon deleted successfully' };
        break;
      }

      default:
        return new Response(
          JSON.stringify({ error: `Unknown operation: ${operation}` }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
    }

    return new Response(
      JSON.stringify(result),
      { 
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      }
    );

  } catch (error) {
    console.error('Coupon management error:', error);
    return new Response(
      JSON.stringify({ 
        error: ((error instanceof Error ? error.message : String(error))) || 'Internal server error',
        details: String(error)
      }),
      { 
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      }
    );
  }
});
