import { z } from 'zod';
import { REQUEST_TRANSITIONS } from '../../maintenance/maintenance.constants';
import { referenceOptions } from '../reference-lookup';
import { router, withPermission } from '../trpc';

const money = z.string().regex(/^\d+(\.\d{1,2})?$/);

/** Resolve maintenance category/priority reference-value ids → display names. */
async function refNameMap(ctx: { prisma: any; organizationId: string | null }): Promise<Map<string, string>> {
  const refs = await ctx.prisma.referenceValue.findMany({
    where: {
      organizationId: ctx.organizationId ?? undefined,
      domain: { in: ['MAINTENANCE_CATEGORY', 'MAINTENANCE_PRIORITY'] },
    },
    select: { id: true, nameEn: true },
  });
  return new Map(refs.map((r: { id: string; nameEn: string }) => [r.id, r.nameEn]));
}

export const maintenanceRouter = router({
  list: withPermission('maintenance.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.maintenanceRequest.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: { createdAt: 'desc' },
      take: 200,
      include: {
        property: { select: { name: true } },
        unit: { select: { name: true } },
        tenant: { select: { name: true } },
        tasks: { select: { id: true } },
      },
    });
    const refName = await refNameMap(ctx);
    return rows.map((r) => ({
      id: r.id,
      title: r.title,
      status: r.status,
      propertyName: r.property.name,
      unitName: r.unit?.name ?? null,
      tenantName: r.tenant?.name ?? null,
      category: r.categoryId ? refName.get(r.categoryId) ?? null : null,
      priority: r.priorityId ? refName.get(r.priorityId) ?? null : null,
      costResponsibility: r.costResponsibility,
      estimatedCost: r.estimatedCost ? r.estimatedCost.toFixed(2) : null,
      actualCost: r.actualCost ? r.actualCost.toFixed(2) : null,
      charged: Boolean(r.chargedInvoiceId),
      taskCount: r.tasks.length,
      createdAt: r.createdAt,
    }));
  }),

  get: withPermission('maintenance.read')
    .input(z.object({ id: z.string() }))
    .query(async ({ ctx, input }) => {
      const r = await ctx.prisma.maintenanceRequest.findFirst({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
        include: {
          property: { select: { name: true } },
          unit: { select: { name: true } },
          tenant: { select: { name: true } },
          lease: { select: { reference: true } },
          tasks: { orderBy: { createdAt: 'asc' }, include: { assignedTo: { select: { name: true } } } },
        },
      });
      if (!r) return null;
      // The repair slips and receipts behind it — carried onto the debit note
      // line when the repair is charged to the tenant. Types are reference
      // values, resolved without the isActive filter the picker uses: a kind
      // retired since is still what this file is.
      const files = await ctx.prisma.attachment.findMany({
        where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'MAINTENANCE_REQUEST', ownerId: r.id },
        orderBy: { createdAt: 'asc' },
      });
      const [types, uploaders] = await Promise.all([
        ctx.prisma.referenceValue.findMany({
          where: { id: { in: files.map((f) => f.documentTypeId).filter((v): v is string => !!v) } },
          select: { id: true, nameEn: true, nameZh: true },
        }),
        ctx.prisma.user.findMany({
          where: { id: { in: files.map((f) => f.uploadedByUserId).filter((v): v is string => !!v) } },
          select: { id: true, name: true },
        }),
      ]);
      const typeById = new Map(types.map((x) => [x.id, x]));
      const uploaderById = new Map(uploaders.map((u) => [u.id, u.name]));
      return {
        id: r.id,
        title: r.title,
        description: r.description,
        status: r.status,
        propertyId: r.propertyId,
        propertyName: r.property.name,
        unitId: r.unitId,
        unitName: r.unit?.name ?? null,
        tenantName: r.tenant?.name ?? null,
        leaseId: r.leaseId,
        leaseRef: r.lease?.reference ?? null,
        categoryId: r.categoryId,
        priorityId: r.priorityId,
        costResponsibility: r.costResponsibility,
        tenantSharePercent: r.tenantSharePercent.toString(),
        estimatedCost: r.estimatedCost ? r.estimatedCost.toFixed(2) : null,
        actualCost: r.actualCost ? r.actualCost.toFixed(2) : null,
        chargedInvoiceId: r.chargedInvoiceId,
        createdAt: r.createdAt,
        allowedTransitions: REQUEST_TRANSITIONS[r.status] ?? [],
        tasks: r.tasks.map((t) => ({
          id: t.id,
          title: t.title,
          status: t.status,
          assignedTo: t.assignedTo?.name ?? null,
          assignedVendor: t.assignedVendor,
          scheduledDate: t.scheduledDate,
          note: t.note,
        })),
        attachments: files.map((f) => ({
          id: f.id,
          filename: f.filename,
          mimeType: f.mimeType,
          sizeBytes: f.sizeBytes,
          caption: f.caption,
          typeNameEn: (f.documentTypeId ? typeById.get(f.documentTypeId)?.nameEn : null) ?? null,
          typeNameZh: (f.documentTypeId ? typeById.get(f.documentTypeId)?.nameZh : null) ?? null,
          uploadedByName: f.uploadedByUserId ? uploaderById.get(f.uploadedByUserId) ?? null : null,
          createdAt: f.createdAt,
        })),
      };
    }),

  /** Option lists for the create/edit forms, org-scoped. */
  formData: withPermission('maintenance.read').query(async ({ ctx }) => {
    const org = ctx.organizationId ?? undefined;
    const [properties, tenants, leases, staff, refs, documentTypes] = await Promise.all([
      ctx.prisma.property.findMany({
        where: { organizationId: org, deletedAt: null },
        orderBy: [{ name: 'asc' }, { code: 'asc' }],
        select: { id: true, name: true, code: true, units: { where: { deletedAt: null }, select: { id: true, name: true } } },
      }),
      ctx.prisma.tenant.findMany({
        where: { organizationId: org, deletedAt: null },
        orderBy: { name: 'asc' },
        select: { id: true, name: true },
      }),
      ctx.prisma.lease.findMany({
        where: { organizationId: org, status: 'ACTIVE', deletedAt: null },
        orderBy: { reference: 'asc' },
        select: {
          id: true,
          reference: true,
          tenantId: true,
          tenant: { select: { name: true, codes: { select: { landlordId: true, code: true } } } },
          units: { select: { unitId: true, unit: { select: { propertyId: true, property: { select: { landlordId: true } } } } } },
        },
      }),
      ctx.prisma.user.findMany({
        where: { deletedAt: null, tenantId: null },
        orderBy: { name: 'asc' },
        select: { id: true, name: true },
      }),
      ctx.prisma.referenceValue.findMany({
        where: { organizationId: org, domain: { in: ['MAINTENANCE_CATEGORY', 'MAINTENANCE_PRIORITY'] }, isActive: true },
        orderBy: { sortOrder: 'asc' },
        select: { id: true, nameEn: true, domain: true },
      }),
      referenceOptions(ctx.prisma, org, 'MAINTENANCE_DOCUMENT_TYPE'),
    ]);
    return {
      properties,
      tenants,
      leases: leases.map((l) => ({
        id: l.id,
        reference: l.reference,
        tenantId: l.tenantId,
        tenantName: l.tenant.name,
        /** The tenant's code in the books of the lease's landlord company —
         *  the one the office files the tenancy under. */
        tenantCode: l.tenant.codes.find((c) => c.landlordId === l.units[0]?.unit.property.landlordId)?.code ?? null,
        // A lease can take units from several purchases of its building.
        propertyIds: [...new Set(l.units.map((u) => u.unit.propertyId))],
        unitIds: l.units.map((u) => u.unitId),
      })),
      documentTypes,
      staff,
      categories: refs.filter((r) => r.domain === 'MAINTENANCE_CATEGORY').map((r) => ({ id: r.id, name: r.nameEn })),
      priorities: refs.filter((r) => r.domain === 'MAINTENANCE_PRIORITY').map((r) => ({ id: r.id, name: r.nameEn })),
    };
  }),

  create: withPermission('maintenance.create')
    .input(
      z.object({
        propertyId: z.string(),
        unitId: z.string().optional(),
        tenantId: z.string().optional(),
        leaseId: z.string().optional(),
        categoryId: z.string().optional(),
        priorityId: z.string().optional(),
        title: z.string().min(1),
        description: z.string().optional(),
        costResponsibility: z.enum(['LANDLORD', 'TENANT', 'SPLIT']).optional(),
        tenantSharePercent: z.string().regex(/^\d+(\.\d{1,3})?$/).optional(),
        estimatedCost: money.optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.maintenance.create({ organizationId: ctx.organizationId ?? '', reportedByUserId: ctx.user.id, ...input }),
    ),

  update: withPermission('maintenance.update')
    .input(
      z.object({
        id: z.string(),
        categoryId: z.string().nullable().optional(),
        priorityId: z.string().nullable().optional(),
        title: z.string().min(1).optional(),
        description: z.string().nullable().optional(),
        leaseId: z.string().nullable().optional(),
        costResponsibility: z.enum(['LANDLORD', 'TENANT', 'SPLIT']).optional(),
        tenantSharePercent: z.string().regex(/^\d+(\.\d{1,3})?$/).optional(),
        estimatedCost: money.nullable().optional(),
        actualCost: money.nullable().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.maintenance.update({ organizationId: ctx.organizationId ?? '', ...input }),
    ),

  transition: withPermission('maintenance.update')
    .input(z.object({ id: z.string(), toStatus: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.maintenance.transition({ organizationId: ctx.organizationId ?? '', ...input }),
    ),

  addTask: withPermission('maintenance.update')
    .input(
      z.object({
        requestId: z.string(),
        title: z.string().min(1),
        assignedToId: z.string().optional(),
        assignedVendor: z.string().optional(),
        scheduledDate: z.string().optional(),
        note: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.maintenance.addTask({ organizationId: ctx.organizationId ?? '', ...input }),
    ),

  updateTask: withPermission('maintenance.update')
    .input(
      z.object({
        taskId: z.string(),
        title: z.string().min(1).optional(),
        status: z.string().optional(),
        assignedToId: z.string().nullable().optional(),
        assignedVendor: z.string().nullable().optional(),
        scheduledDate: z.string().nullable().optional(),
        note: z.string().nullable().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.maintenance.updateTask({ organizationId: ctx.organizationId ?? '', ...input }),
    ),

  /** Push a tenant-borne cost onto a reviewable R&M draft invoice. */
  chargeToTenant: withPermission('invoice.create')
    .input(z.object({ id: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.maintenance.chargeToTenant({ organizationId: ctx.organizationId ?? '', id: input.id }),
    ),
});
