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

export const POST: APIRoute = async ({ request }) => {
  try {
    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 { storeName, storeDescription, storePhone, bankAccount, bankName } = body;
    
    if (!storeName) {
      return new Response(JSON.stringify({ error: 'Store name is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: existingVendor } = await supabaseAdmin
      .from('vendor_profiles')
      .select('id')
      .eq('user_id', payload.userId)
      .single();
    
    if (existingVendor) {
      return new Response(JSON.stringify({ error: 'You already have a vendor profile' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    let storeSlug = storeName
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '')
      .substring(0, 50);
    
    const { data: existingSlug } = await supabaseAdmin
      .from('vendor_profiles')
      .select('store_slug')
      .like('store_slug', `${storeSlug}%`);
    
    if (existingSlug && existingSlug.length > 0) {
      storeSlug = `${storeSlug}-${existingSlug.length + 1}`;
    }
    
    const { data: vendor, error } = await supabaseAdmin
      .from('vendor_profiles')
      .insert({
        user_id: payload.userId,
        store_name: storeName,
        store_slug: storeSlug,
        store_description: storeDescription || null,
        store_phone: storePhone || null,
        bank_account: bankAccount || null,
        bank_name: bankName || null,
        payout_status: 'pending'
      })
      .select()
      .single();
    
    if (error) {
      throw error;
    }
    
    await supabaseAdmin
      .from('users')
      .update({ role: 'vendor' })
      .eq('id', payload.userId);
    
    return new Response(JSON.stringify({
      success: true,
      vendor,
      message: 'Vendor application submitted successfully'
    }), {
      status: 201,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Vendor apply error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
