import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Try to fetch actual onboard data from profile table
    let onboardData = {
      id: 'default-onboard-id',
      companyName: '',
      currency: '',
      dateOfBirth: '',
      headline: '',
      aboutYourself: '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    try {
      // Get user and profile data from database
      const user = await prisma.user.findUnique({
        where: { email: session.user.email },
        include: {
          profile: true
        }
      });

      if (user?.profile) {
        // Parse additional data from address field
        let additionalData = {
          companyName: '',
          currency: 'EUR',
          dateOfBirth: '',
          onboardCompleted: false
        };

        try {
          if (user.profile.address) {
            const parsed = JSON.parse(user.profile.address);
            additionalData = { ...additionalData, ...parsed };
          }
        } catch (parseError) {
          console.log('Could not parse additional onboard data');
        }

        // Map profile data to onboard format
        onboardData = {
          id: user.profile.id,
          companyName: additionalData.companyName || '',
          currency: additionalData.currency || 'EUR',
          dateOfBirth: additionalData.dateOfBirth || '',
          headline: user.profile.title || '',
          aboutYourself: user.profile.bio || '',
          createdAt: user.profile.createdAt.toISOString(),
          updatedAt: user.profile.updatedAt.toISOString()
        };
      }
    } catch (dbError) {
      console.log('Database not available, using fallback onboard data');
      // Keep default empty onboard data
    }

    return NextResponse.json({
      success: true,
      data: onboardData
    });

  } catch (error) {
    console.error('Error fetching onboard data:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch onboard data',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { 
      companyName, 
      currency, 
      dateOfBirth, 
      headline, 
      aboutYourself 
    } = body;

    // Validate required fields
    if (!dateOfBirth || !aboutYourself) {
      return NextResponse.json(
        { error: 'Date of Birth and About Yourself are required' },
        { status: 400 }
      );
    }

    // Debug logging
    console.log('Onboard data received:', {
      companyName,
      currency,
      dateOfBirth,
      headline,
      aboutYourself
    });

    // Try to save actual onboard data to profile table
    let savedOnboardData = {
      id: `fallback-onboard-${Date.now()}`,
      companyName: companyName || '',
      currency: currency || 'EUR',
      dateOfBirth: dateOfBirth,
      headline: headline || '',
      aboutYourself: aboutYourself,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    try {
      // Get user from database
      const user = await prisma.user.findUnique({
        where: { email: session.user.email },
        select: { id: true }
      });

      if (user) {
        // Update or create profile with onboard data
        // Store additional data in a JSON format in the address field temporarily
        const additionalData = JSON.stringify({
          companyName: companyName || '',
          currency: currency || 'EUR',
          dateOfBirth: dateOfBirth || '',
          onboardCompleted: true
        });

        const updatedProfile = await prisma.profile.upsert({
          where: { userId: user.id },
          update: {
            title: headline || null, // Store headline in title field
            bio: aboutYourself, // Store aboutYourself in bio field
            address: additionalData, // Store additional onboard data as JSON
          },
          create: {
            userId: user.id,
            countryId: 'switzerland', // Default country
            title: headline || null,
            bio: aboutYourself,
            address: additionalData,
          }
        });

        // Debug logging
        console.log('Profile updated with onboard data:', {
          id: updatedProfile.id,
          title: updatedProfile.title,
          bio: updatedProfile.bio
        });

        // Parse the saved additional data for response
        let storedAdditionalData = {
          companyName: companyName || '',
          currency: currency || 'EUR',
          dateOfBirth: dateOfBirth || ''
        };

        try {
          if (updatedProfile.address) {
            const parsed = JSON.parse(updatedProfile.address);
            storedAdditionalData = { ...storedAdditionalData, ...parsed };
          }
        } catch (parseError) {
          console.log('Could not parse stored additional data');
        }

        // Use actual saved data for response
        savedOnboardData = {
          id: updatedProfile.id,
          companyName: storedAdditionalData.companyName || '',
          currency: storedAdditionalData.currency || 'EUR',
          dateOfBirth: storedAdditionalData.dateOfBirth || '',
          headline: updatedProfile.title || headline || '',
          aboutYourself: updatedProfile.bio || aboutYourself,
          createdAt: updatedProfile.createdAt.toISOString(),
          updatedAt: updatedProfile.updatedAt.toISOString()
        };
      }
    } catch (dbError) {
      console.error('Database error saving onboard data:', dbError);
      // Keep fallback data, but still return success so user experience isn't broken
    }

    return NextResponse.json({
      success: true,
      data: savedOnboardData,
      message: 'Onboard information saved successfully'
    });

  } catch (error) {
    console.error('Error saving onboard data:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to save onboard data',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

export async function PUT(req: NextRequest) {
  // PUT method delegates to POST for upsert functionality
  return POST(req);
}