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

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);

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

    const body = await request.json();
    const { id } = params;

    const location = await prisma.location.update({
      where: { id },
      data: {
        imapHost: body.imapHost || null,
        imapPort: body.imapPort || null,
        imapUser: body.imapUser || null,
        imapPassword: body.imapPassword || null,
        imapSecure: body.imapSecure ?? true,
        smtpHost: body.smtpHost || null,
        smtpPort: body.smtpPort || null,
        smtpUser: body.smtpUser || null,
        smtpPassword: body.smtpPassword || null,
        smtpSecure: body.smtpSecure ?? true,
        emailSyncEnabled: body.emailSyncEnabled ?? false,
      },
    });

    return NextResponse.json({ success: true, location });
  } catch (error) {
    console.error('Email settings update error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
