import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { verifyAdminAuth } from '@/lib/admin-auth';

export async function GET(request: NextRequest) {
  try {
    const adminUser = await verifyAdminAuth(request);
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const socialMediaLinks = await prisma.socialMediaLink.findMany({
      orderBy: { order: 'asc' },
      include: {
        creator: { select: { name: true, email: true } },
        updater: { select: { name: true, email: true } }
      }
    });

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

export async function POST(request: NextRequest) {
  try {
    const adminUser = await verifyAdminAuth(request);
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const {
      platform,
      name,
      url,
      icon,
      isEnabled = true,
      order = 0
    } = body;

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

    // Check if platform already exists
    const existingLink = await prisma.socialMediaLink.findUnique({
      where: { platform }
    });

    if (existingLink) {
      return NextResponse.json(
        { success: false, error: 'A social media link for this platform already exists' },
        { status: 400 }
      );
    }

    const socialMediaLink = await prisma.socialMediaLink.create({
      data: {
        platform,
        name,
        url,
        icon,
        isEnabled,
        order,
        createdBy: adminUser.id,
        updatedBy: adminUser.id
      },
      include: {
        creator: { select: { name: true, email: true } },
        updater: { select: { name: true, email: true } }
      }
    });

    return NextResponse.json({
      success: true,
      data: socialMediaLink
    });
  } catch (error) {
    console.error('Error creating social media link:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to create social media link' },
      { status: 500 }
    );
  }
}