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

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

    const configs = await prisma.whiteLabelConfig.findMany({
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json({ configs });
  } catch (error) {
    console.error('Error fetching white-label configs:', error);
    return NextResponse.json(
      { error: 'Failed to fetch white-label configs' },
      { status: 500 }
    );
  }
}

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

    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
    });

    if (!user || user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
    }

    const body = await req.json();
    const {
      organizationId,
      organizationName,
      primaryColor,
      secondaryColor,
      logo,
      faviconUrl,
      customDomain,
      defaultRegion,
      supportedRegions,
      defaultCurrency,
      enabledFeatures,
      supportEmail,
      supportPhone,
    } = body;

    if (!organizationId || !organizationName || !primaryColor || !secondaryColor) {
      return NextResponse.json(
        { error: 'Organization details and branding are required' },
        { status: 400 }
      );
    }

    const config = await prisma.whiteLabelConfig.create({
      data: {
        organizationId,
        organizationName,
        primaryColor,
        secondaryColor,
        logo,
        faviconUrl,
        customDomain,
        defaultRegion: defaultRegion || 'SOUTH_AFRICA',
        supportedRegions: supportedRegions || ['SOUTH_AFRICA'],
        defaultCurrency: defaultCurrency || 'ZAR',
        enabledFeatures: enabledFeatures || {},
        supportEmail,
        supportPhone,
      },
    });

    return NextResponse.json({ config }, { status: 201 });
  } catch (error) {
    console.error('Error creating white-label config:', error);
    return NextResponse.json(
      { error: 'Failed to create white-label config' },
      { status: 500 }
    );
  }
}
