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

// PATCH /api/calendar/cross-sync/rules/[id] — update a rule
export async function PATCH(request: NextRequest, { params }: { params: { id: string } }) {
  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 existing = await prisma.calendarSyncRule.findFirst({ where: { id: params.id, userId: user.id } });
  if (!existing) return NextResponse.json({ error: 'Rule not found' }, { status: 404 });

  const body = await request.json();
  const allowed = ['name', 'enabled', 'direction', 'sourceConnectionId', 'sourceCalendarId',
    'targetConnectionId', 'targetCalendarId', 'syncDescription', 'syncLocation',
    'syncRecurring', 'titlePrefix'];

  const data: Record<string, any> = {};
  for (const key of allowed) {
    if (key in body) data[key] = body[key];
  }

  const rule = await prisma.calendarSyncRule.update({ where: { id: params.id }, data });
  return NextResponse.json({ rule });
}

// DELETE /api/calendar/cross-sync/rules/[id] — delete a rule and all its mappings
export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
  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 existing = await prisma.calendarSyncRule.findFirst({ where: { id: params.id, userId: user.id } });
  if (!existing) return NextResponse.json({ error: 'Rule not found' }, { status: 404 });

  // Cascade delete (mappings deleted via onDelete: Cascade in schema)
  await prisma.calendarSyncRule.delete({ where: { id: params.id } });
  // Also clean up reverse mappings stored under the synthetic _R id
  await prisma.calendarSyncMapping.deleteMany({ where: { ruleId: params.id + '_R' } });

  return NextResponse.json({ success: true });
}
