import { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { NOTIFICATION_CHANNELS, NOTIFICATION_EVENTS, NOTIFICATION_RECIPIENTS } from '../../notifications/notification.constants';
import { router, withPermission } from '../trpc';

const eventEnum = z.enum(['INVOICE_ISSUED', 'RECEIPT_APPROVED', 'RECEIPT_REJECTED', 'RECEIPT_BOUNCED', 'MAINTENANCE_STATUS_CHANGED', 'STATEMENT_SENT']);
const channelEnum = z.enum(['EMAIL', 'SMS']);
const recipientEnum = z.enum(['TENANT', 'STAFF']);

export const notificationsRouter = router({
  /** Drives the template editor: which events exist and their placeholders. */
  meta: withPermission('setting.read').query(() => ({
    events: NOTIFICATION_EVENTS,
    channels: NOTIFICATION_CHANNELS,
    recipients: NOTIFICATION_RECIPIENTS,
  })),

  templates: withPermission('setting.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.notificationTemplate.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: [{ event: 'asc' }, { channel: 'asc' }, { locale: 'asc' }, { recipient: 'asc' }],
    });
    return rows.map((t) => ({
      id: t.id,
      event: t.event,
      channel: t.channel,
      locale: t.locale,
      recipient: t.recipient,
      subject: t.subject,
      body: t.body,
      isActive: t.isActive,
      updatedAt: t.updatedAt,
    }));
  }),

  upsertTemplate: withPermission('setting.update')
    .input(
      z.object({
        id: z.string().optional(),
        event: eventEnum,
        channel: channelEnum,
        locale: z.string().min(1).default('zh'),
        recipient: recipientEnum.default('TENANT'),
        subject: z.string().optional(),
        body: z.string().min(1),
        isActive: z.boolean().default(true),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const data = {
        event: input.event,
        channel: input.channel,
        locale: input.locale,
        recipient: input.recipient,
        subject: input.subject ?? null,
        body: input.body,
        isActive: input.isActive,
      };
      try {
        if (input.id) {
          await ctx.prisma.notificationTemplate.update({ where: { id: input.id }, data });
        } else {
          await ctx.prisma.notificationTemplate.upsert({
            where: {
              organizationId_event_channel_locale_recipient: {
                organizationId,
                event: input.event,
                channel: input.channel,
                locale: input.locale,
                recipient: input.recipient,
              },
            },
            update: { subject: input.subject ?? null, body: input.body, isActive: input.isActive },
            create: { organizationId, ...data },
          });
        }
      } catch (err) {
        if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
          throw new TRPCError({
            code: 'CONFLICT',
            message: 'A template already exists for that event / channel / locale / recipient',
          });
        }
        throw err;
      }
      return { ok: true };
    }),

  /** The append-only delivery log — every attempt with its status. */
  outbox: withPermission('setting.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.notificationOutbox.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: { createdAt: 'desc' },
      take: 100,
    });
    return rows.map((o) => ({
      id: o.id,
      event: o.event,
      channel: o.channel,
      recipient: o.recipient,
      subject: o.subject,
      status: o.status,
      error: o.error,
      createdAt: o.createdAt,
      sentAt: o.sentAt,
    }));
  }),
});
