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

// GET /api/calendar/cross-sync/rules — list all rules for the current user
export async function GET(request: NextRequest) {
  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 }, select: { id: true } });
  if (!user) return NextResponse.json({ error: 'User not found' }, { status: 404 });

  const rules = await prisma.calendarSyncRule.findMany({
    where: { userId: user.id },
    orderBy: { createdAt: 'asc' },
  });

  return NextResponse.json({ rules });
}

// POST /api/calendar/cross-sync/rules — create a new rule
export async function POST(request: NextRequest) {
  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 }, select: { id: true } });
  if (!user) return NextResponse.json({ error: 'User not found' }, { status: 404 });

  const body = await request.json();
  const {
    name = '',
    enabled = true,
    direction = 'one-way',
    sourceConnectionId,
    sourceCalendarId,
    targetConnectionId,
    targetCalendarId,
    syncDescription = true,
    syncLocation = true,
    syncRecurring = false,
    titlePrefix = '',
  } = body;

  if (!sourceConnectionId || !sourceCalendarId || !targetConnectionId || !targetCalendarId) {
    return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
  }

  // Verify connections belong to this user
  const connCount = await prisma.calendarConnection.count({
    where: { id: { in: [sourceConnectionId, targetConnectionId] }, userId: user.id },
  });
  if (connCount < 2) {
    return NextResponse.json({ error: 'Invalid connection IDs' }, { status: 403 });
  }

  const rule = await prisma.calendarSyncRule.create({
    data: {
      userId: user.id,
      name,
      enabled,
      direction,
      sourceConnectionId,
      sourceCalendarId,
      targetConnectionId,
      targetCalendarId,
      syncDescription,
      syncLocation,
      syncRecurring,
      titlePrefix,
    },
  });

  return NextResponse.json({ rule }, { status: 201 });
}
