import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { upsertSetting } from '@/lib/services/settings.service';
import {
  EMAIL_CATEGORIES,
  EMAIL_ROUTING_KEY,
  getEmailRoutingMatrix,
} from '@/lib/services/email-routing';

const senderSchema = z.enum(['noreply', 'sales']);
const updateSchema = z.object({
  routing: z.record(z.enum(EMAIL_CATEGORIES), senderSchema),
});

export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      const matrix = await getEmailRoutingMatrix(ctx.portId);
      return NextResponse.json({
        data: { ...matrix, categories: EMAIL_CATEGORIES },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PATCH = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const input = await parseBody(req, updateSchema);
      await upsertSetting(EMAIL_ROUTING_KEY, input.routing, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      const matrix = await getEmailRoutingMatrix(ctx.portId);
      return NextResponse.json({
        data: { ...matrix, categories: EMAIL_CATEGORIES },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
