import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { toggleAccount, disconnectAccount } from '@/lib/services/email-accounts.service';
import { toggleAccountSchema } from '@/lib/validators/email';

export const PATCH = withAuth(
  withPermission('email', 'configure_account', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, toggleAccountSchema);
      const account = await toggleAccount(params.accountId!, ctx.userId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: account });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('email', 'configure_account', async (_req, ctx, params) => {
    try {
      await disconnectAccount(params.accountId!, ctx.userId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
