export const prerender = false;

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

const signupSchema = z.object({
  organization_name: z.string().min(1).max(255),
  business_type: z.enum(['individual', 'company']).default('individual'),
  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 POST: 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;
    
    // Check if user already has an organization
    const { data: existingUser, error: userError } = await supabase
      .from('users')
      .select('organization_id')
      .eq('id', user.id)
      .single();

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

    if (existingUser?.organization_id) {
      return new Response(JSON.stringify({ error: 'User already has an organization' }), { 
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Parse and validate request body
    const body = await request.json();
    const validationResult = signupSchema.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 { organization_name, ...profileData } = validationResult.data;

    // Clean up empty strings to null for optional fields
    const cleanedData = Object.entries(profileData).reduce((acc, [key, value]) => {
      if (value === '') {
        acc[key] = null;
      } else {
        acc[key] = value;
      }
      return acc;
    }, {} as Record<string, unknown>);

    // Create organization
    const { data: organization, error: orgError } = await supabase
      .from('organizations')
      .insert({
        name: organization_name,
        ...cleanedData,
        account_status: 'pending_approval',
        approval_score: 0
      })
      .select()
      .single();

    if (orgError) {
      // Log error for debugging
      console.error('Failed to create organization:', orgError);
      return new Response(JSON.stringify({ error: 'Failed to create organization' }), { 
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Update user with organization ID
    const { error: updateUserError } = await supabase
      .from('users')
      .update({ organization_id: organization.id })
      .eq('id', user.id);

    if (updateUserError) {
      // Log error and cleanup
      console.error('Failed to update user with organization ID:', updateUserError);
      // Try to cleanup the organization
      await supabase.from('organizations').delete().eq('id', organization.id);
      return new Response(JSON.stringify({ error: 'Failed to complete organization setup' }), { 
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Calculate approval score and process auto-approval
    const { error: scoreError } = await supabase
      .rpc('calculate_approval_score', { org_id: organization.id });

    if (scoreError) {
      // Log error but don't fail the request
      console.warn('Failed to calculate approval score:', scoreError);
    }

    // Process auto-approval
    const { data: autoApprovalResult, error: autoApprovalError } = await supabase
      .rpc('process_auto_approval', { org_id: organization.id });

    if (autoApprovalError) {
      // Log error but don't fail the request
      console.warn('Failed to process auto-approval:', autoApprovalError);
    }

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

    if (refreshError) {
      // Log error but use original organization data
      console.warn('Failed to refresh organization data:', refreshError);
    }

    const finalOrg = updatedOrg || organization;

    // Log the signup
    await logUserActivity({
      userId: user.id,
      action: 'organization_created',
      resourceType: 'organization',
      resourceId: organization.id,
      details: { 
        organization_name,
        business_type: cleanedData.business_type,
        auto_approved: autoApprovalResult || false,
        approval_score: finalOrg.approval_score
      }
    });

    // Send appropriate email notification
    try {
      if (finalOrg.account_status === 'approved') {
        // Send approval notification email
        const response = await fetch(`${request.url.replace(/\/api\/.*/, '')}/api/emails/send-approval-notification`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': request.headers.get('Authorization') || ''
          },
          body: JSON.stringify({
            organization_id: organization.id,
            auto_approved: true
          })
        });

        if (!response.ok) {
          // Log email sending failure but don't fail the request
          console.warn('Failed to send approval notification email');
        }
      } else {
        // Send application received email
        const response = await fetch(`${request.url.replace(/\/api\/.*/, '')}/api/emails/send-application-received`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': request.headers.get('Authorization') || ''
          },
          body: JSON.stringify({
            organization_id: organization.id
          })
        });

        if (!response.ok) {
          // Log email sending failure but don't fail the request
          console.warn('Failed to send application received email');
        }

        // Send admin notification email
        const adminResponse = await fetch(`${request.url.replace(/\/api\/.*/, '')}/api/emails/send-admin-notification`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': request.headers.get('Authorization') || ''
          },
          body: JSON.stringify({
            organization_id: organization.id
          })
        });

        if (!adminResponse.ok) {
          // Log email sending failure but don't fail the request
          console.warn('Failed to send admin notification email');
        }
      }
    } catch (emailError) {
      // Log email error but don't fail the request
      console.warn('Email notification error:', emailError);
      // Don't fail the request for email errors
    }

    return new Response(JSON.stringify({
      success: true,
      organization: finalOrg,
      auto_approved: finalOrg.account_status === 'approved',
      message: finalOrg.account_status === 'approved' 
        ? 'Organization created and auto-approved! You can now start Stripe onboarding.'
        : 'Organization created successfully. Your application is pending approval.'
    }), {
      status: 201,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {
    // Log error for debugging
    console.error('Failed to process organization signup:', error);
    return new Response(JSON.stringify({ 
      error: 'Failed to process organization signup',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), { 
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};