export const prerender = false;

import type { APIRoute } from 'astro';
import { supabase, supabaseAdmin } from '../../../lib/supabase';
import { verifyAuth } from '../../../lib/auth';
import { logUserActivity } from '../../../lib/logger';
import { z } from 'zod';

const updateProfileSchema = z.object({
  name: z.string().min(1).max(255),
  business_type: z.enum(['individual', 'company']).optional(),
  business_description: z.string().max(500).optional(),
  website_url: z.string().url().optional().or(z.literal('')),
  phone_number: z.string().max(20).optional(),
  address_line1: z.string().max(255).optional(),
  address_line2: z.string().max(255).optional(),
  city: z.string().max(100).optional(),
  state: z.string().max(50).optional(),
  postal_code: z.string().max(20).optional(),
  country: z.string().length(2).default('US')
});

export const PUT: APIRoute = async ({ request }) => {
  try {
    // Verify authentication
    const authContext = await verifyAuth(request);
    if (!authContext) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), { 
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const { user } = authContext;
    
    // Get user's organization ID first (using admin client to bypass RLS)
    const { data: userData, error: userError } = await (supabaseAdmin || supabase)
      .from('users')
      .select('organization_id')
      .eq('id', user.id)
      .single();

    if (userError || !userData?.organization_id) {
      return new Response(JSON.stringify({ error: 'Organization not found' }), { 
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Now get the organization details
    const { data: organization, error: orgError } = await (supabaseAdmin || supabase)
      .from('organizations')
      .select('*')
      .eq('id', userData.organization_id)
      .single();

    if (orgError || !organization) {
      return new Response(JSON.stringify({ error: 'Organization details not found' }), { 
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Parse and validate request body
    const body = await request.json();
    const validationResult = updateProfileSchema.safeParse(body);

    if (!validationResult.success) {
      return new Response(JSON.stringify({ 
        error: 'Invalid request data',
        details: validationResult.error.errors
      }), { 
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const updateData = validationResult.data;

    // Clean up empty strings to null for optional fields
    const cleanedData = Object.entries(updateData).reduce((acc, [key, value]) => {
      if (value === '' && key !== 'name') {
        acc[key] = null;
      } else {
        acc[key] = value;
      }
      return acc;
    }, {} as any);

    // Update organization
    const { data: updatedOrg, error: updateError } = await (supabaseAdmin || supabase)
      .from('organizations')
      .update(cleanedData)
      .eq('id', organization.id)
      .select()
      .single();

    if (updateError) {

      return new Response(JSON.stringify({ error: 'Failed to update organization' }), { 
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Recalculate approval score after profile update
    const { error: scoreError } = await (supabaseAdmin || supabase)
      .rpc('calculate_approval_score', { org_id: organization.id });

    if (scoreError) {

    }

    // Check if organization should be auto-approved after profile update
    if (organization.account_status === 'pending_approval') {
      const { error: autoApprovalError } = await (supabaseAdmin || supabase)
        .rpc('process_auto_approval', { org_id: organization.id });

      if (autoApprovalError) {

      }
    }

    // Log the profile update
    await logUserActivity({
      userId: user.id,
      action: 'organization_profile_updated',
      resourceType: 'organization',
      resourceId: organization.id,
      details: { 
        updated_fields: Object.keys(cleanedData),
        previous_status: organization.account_status
      }
    });

    // Get updated organization with new approval score
    const { data: refreshedOrg, error: refreshError } = await (supabaseAdmin || supabase)
      .from('organizations')
      .select('*')
      .eq('id', organization.id)
      .single();

    if (refreshError) {

    }

    return new Response(JSON.stringify({
      success: true,
      organization: refreshedOrg || updatedOrg,
      message: 'Organization profile updated successfully'
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {

    return new Response(JSON.stringify({ 
      error: 'Failed to update organization profile',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), { 
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};