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 { listAccounts, connectAccount } from '@/lib/services/email-accounts.service';
import { connectAccountSchema } from '@/lib/validators/email';

export const GET = withAuth(
  withPermission('email', 'view', async (_req, ctx) => {
    try {
      const accounts = await listAccounts(ctx.userId, ctx.portId);
      return NextResponse.json({ data: accounts });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('email', 'configure_account', async (req, ctx) => {
    try {
      const body = await parseBody(req, connectAccountSchema);
      const account = await connectAccount(ctx.userId, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: account }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
