import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { hkDay } from '../../common/hk-date';
import { NUMBER_PARTS, RESET_PERIODS, parseParts, partsRequiredBy, periodOf } from '../../common/number-format';
import { NUMBERED_DOCS, previewNumber } from '../../common/number.service';
import { router, withPermission } from '../trpc';

/** Letters, digits and - _ / . , up to 20 — what a symbol or special string may hold. */
const PREFIX = /^[A-Za-z0-9\-_/.]{0,20}$/;

/**
 * How each document is numbered, laid out as the ERP's document-number
 * formatting: symbol, two special strings, company code, year, month, day and
 * serial, each shown or not and in the office's order; whether the count
 * restarts; and where this period's counts are up to — one, or one per company
 * when the number carries the company code. Under the Settings permission, as
 * the rest of the organisation's configuration is.
 */
export const numberingRouter = router({
  list: withPermission('setting.read').query(async ({ ctx }) => {
    const organizationId = ctx.organizationId ?? '';
    const now = new Date();
    const today = hkDay(now);
    const [rows, companies] = await Promise.all([
      ctx.prisma.numberSequence.findMany({
        where: { organizationId, docType: { in: [...NUMBERED_DOCS] } },
        // This period's counts under each kind of restart, so the page can show
        // where the count would be up to if the restart were changed.
        include: { counters: { where: { periodKey: { in: ['', periodOf('YEARLY', today), periodOf('MONTHLY', today)] } } } },
      }),
      ctx.prisma.landlord.findMany({
        where: { organizationId, isActive: true, deletedAt: null },
        orderBy: [{ sortOrder: 'asc' }, { code: 'asc' }],
        select: { id: true, code: true, name: true },
      }),
    ]);
    const sequences = await Promise.all(
      NUMBERED_DOCS.flatMap((docType) => {
        const seq = rows.find((r) => r.docType === docType);
        return seq ? [{ docType, seq }] : [];
      }).map(async ({ docType, seq }) => ({
        docType,
        prefix: seq.prefix,
        text1: seq.text1,
        text2: seq.text2,
        parts: parseParts(seq.parts),
        padding: seq.padding,
        resetPeriod: seq.resetPeriod,
        /** What the next document will actually be numbered — after any restart
         *  due and any number already typed in by hand; the first company's,
         *  when each company has its own count. */
        next: await previewNumber(ctx.prisma, seq, docType, companies[0] ?? null, now),
        /** This period's counts, as `${periodKey}|${scope}` → the next value; a
         *  count not yet started is not here, and starts at 1. */
        counts: Object.fromEntries(seq.counters.map((c) => [`${c.periodKey}|${c.scope}`, c.nextValue])),
      })),
    );
    return { today, companies, sequences };
  }),

  update: withPermission('setting.update')
    .input(
      z.object({
        docType: z.enum(NUMBERED_DOCS),
        prefix: z.string(),
        text1: z.string(),
        text2: z.string(),
        parts: z.array(z.enum(NUMBER_PARTS)),
        padding: z.number().int().min(1).max(10),
        resetPeriod: z.enum(RESET_PERIODS),
        /** This period's counts to set — the one shared count (landlordId null)
         *  or a company's. Only the ones changed are sent. */
        counts: z.array(z.object({ landlordId: z.string().nullable(), nextValue: z.number().int().min(1).max(99_999_999) })).default([]),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const [prefix, text1, text2] = [input.prefix.trim(), input.text1.trim(), input.text2.trim()];
      if (!PREFIX.test(prefix)) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'A prefix may use only letters, digits and - _ / . — up to 20 characters' });
      }
      if (!PREFIX.test(text1) || !PREFIX.test(text2)) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'A special string may use only letters, digits and - _ / . — up to 20 characters' });
      }
      if (new Set(input.parts).size !== input.parts.length) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'Each part of a number may appear only once' });
      }
      if (!input.parts.includes('SERIAL')) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'A number must include its serial number' });
      }
      if (partsRequiredBy(input.resetPeriod).some((p) => !input.parts.includes(p))) {
        if (input.resetPeriod === 'YEARLY') throw new TRPCError({ code: 'BAD_REQUEST', message: 'A yearly restart needs the year in the number' });
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'A monthly restart needs the year and the month in the number' });
      }

      const seq = await ctx.prisma.numberSequence.findFirst({ where: { organizationId, docType: input.docType }, select: { id: true } });
      if (!seq) throw new TRPCError({ code: 'NOT_FOUND', message: 'Number sequence not found' });
      const landlordIds = [...new Set(input.counts.flatMap((c) => (c.landlordId ? [c.landlordId] : [])))];
      if (landlordIds.length > 0 && (await ctx.prisma.landlord.count({ where: { id: { in: landlordIds }, organizationId } })) !== landlordIds.length) {
        throw new TRPCError({ code: 'NOT_FOUND', message: 'Landlord not found' });
      }

      // A count set here is this period's, so it is the one used now — not
      // passed over by the restart a stale period would trigger.
      const periodKey = periodOf(input.resetPeriod, hkDay(new Date()));
      await ctx.prisma.$transaction([
        ctx.prisma.numberSequence.update({
          where: { id: seq.id },
          data: { prefix, text1, text2, parts: input.parts.join(','), padding: input.padding, resetPeriod: input.resetPeriod },
        }),
        ...input.counts.map((c) => {
          const key = { sequenceId: seq.id, scope: c.landlordId ?? '', periodKey };
          return ctx.prisma.numberCounter.upsert({
            where: { sequenceId_scope_periodKey: key },
            create: { ...key, nextValue: c.nextValue },
            update: { nextValue: c.nextValue },
          });
        }),
      ]);
      return { ok: true };
    }),
});
