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 { sendEmail } from '@/lib/services/email-compose.service';
import { composeEmailSchema } from '@/lib/validators/email';

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