import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const socialMedia = await db.socialMedia.findMany({
      where: {
        isActive: true
      },
      orderBy: {
        order: 'asc'
      }
    });

    return NextResponse.json({
      success: true,
      data: socialMedia
    });
  } catch (error) {
    console.error('Error fetching social media:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch social media' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      platform,
      name,
      url,
      username,
      description,
      icon,
      isActive = true,
      order = 0
    } = body;

    // Validate required fields
    if (!platform || !name || !url) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Platform, name, and URL are required' 
        },
        { status: 400 }
      );
    }

    const socialMedia = await db.socialMedia.create({
      data: {
        platform,
        name,
        url,
        username,
        description,
        icon,
        isActive,
        order
      }
    });

    return NextResponse.json({
      success: true,
      data: socialMedia,
      message: 'Social media created successfully'
    });

  } catch (error) {
    console.error('Error creating social media:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to create social media',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}