import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  NOTIFICATION_BODY_FORMATS,
  NOTIFICATION_CHANNELS,
} from '@/features/foundation/notifications/types';
import { sendNotification } from '@/features/foundation/notifications/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const recipientSchema = z.object({
  email: z.string().email(),
  name: z.string().trim().min(1).optional().nullable(),
});

const attachmentSchema = z.discriminatedUnion('type', [
  z.object({
    type: z.literal('artifact'),
    artifactId: z.string().min(1),
    label: z.string().optional().nullable(),
  }),
  z.object({
    type: z.literal('document_library_version'),
    versionId: z.string().min(1),
    label: z.string().optional().nullable(),
  }),
  z.object({
    type: z.literal('active_document_library'),
    libraryId: z.string().min(1),
    label: z.string().optional().nullable(),
  }),
]);

const sendSchema = z.object({
  eventType: z.string().min(1),
  entityType: z.string().min(1),
  entityId: z.string().min(1),
  channel: z.enum(NOTIFICATION_CHANNELS),
  payload: z.record(z.string(), z.unknown()).optional(),
  templateOverride: z
    .object({
      subjectTemplate: z.string().optional(),
      titleTemplate: z.string().optional(),
      bodyTemplate: z.string().optional(),
      bodyFormat: z.enum(NOTIFICATION_BODY_FORMATS).optional(),
      linkTemplate: z.string().nullable().optional(),
    })
    .optional(),
  recipientOverride: z.object({
    to: z.array(recipientSchema).min(1),
    cc: z.array(recipientSchema).optional(),
    bcc: z.array(recipientSchema).optional(),
    replyTo: z.string().email().nullable().optional(),
    recipientUserId: z.string().nullable().optional(),
  }),
  attachments: z.array(attachmentSchema).optional(),
  providerKey: z.string().optional(),
  maxRetryCount: z.number().int().min(1).max(10).optional(),
});

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationSend,
    });
    const parsed = sendSchema.parse(await request.json());

    const result = await sendNotification({
      organizationId: organization.id,
      actorUserId: session.user.id,
      ...parsed,
    });

    return NextResponse.json({
      message: 'Notification sent successfully',
      dispatch: result,
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: 'Invalid send payload', issues: error.flatten() },
        { status: 400 },
      );
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to send notification' }, { status: 500 });
  }
}
