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

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

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

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    const syncConfig = await prisma.calendarSync.findUnique({
      where: { userId: user.id }
    });

    return NextResponse.json({ syncConfig });
  } catch (error) {
    console.error('Error fetching calendar sync config:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

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

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    const data = await request.json();

    const syncConfig = await prisma.calendarSync.upsert({
      where: { userId: user.id },
      create: {
        userId: user.id,
        provider: data.provider,
        isEnabled: data.isEnabled ?? true,
        syncDirection: data.syncDirection || 'ONE_WAY',
        autoSync: data.autoSync ?? true,
        syncFrequency: data.syncFrequency || 15,
        timezone: data.timezone || 'Africa/Johannesburg',
        calendarName: data.calendarName
      },
      update: {
        provider: data.provider,
        isEnabled: data.isEnabled,
        syncDirection: data.syncDirection,
        autoSync: data.autoSync,
        syncFrequency: data.syncFrequency,
        timezone: data.timezone,
        calendarName: data.calendarName
      }
    });

    return NextResponse.json({ syncConfig });
  } catch (error) {
    console.error('Error updating calendar sync config:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
