import { HttpException } from '@nestjs/common';
import type { AttachmentOwnerType, PrismaClient } from '@prisma/client';
import { type Request, type Response, Router } from 'express';
import multer from 'multer';
import type { AuthService } from '../auth/auth.service';
import type { AttachmentService } from './attachment.service';

const MAX_BYTES = 10 * 1024 * 1024;
const OWNER_TYPES = new Set(['RECEIPT', 'MAINTENANCE_REQUEST', 'LEASE', 'INVOICE', 'INVOICE_LINE', 'METER_READING', 'PROPERTY_NOTICE', 'PROPERTY']);

/**
 * Raw Express routes for binary uploads/downloads — tRPC is JSON-only, so files
 * go through here. Mounted at /api/uploads from main.ts with resolved providers,
 * mirroring the tRPC adapter so router modules stay framework-free.
 */
export function createUploadsRouter(prisma: PrismaClient, authService: AuthService, attachments: AttachmentService) {
  // `defParamCharset`: browsers send the file's name as UTF-8, and multer reads it
  // as latin1 unless told otherwise — so 「維修單.pdf」 arrived as mojibake and was
  // filed as "_.pdf".
  const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_BYTES, files: 1 }, defParamCharset: 'utf8' });
  const router = Router();

  /** Carries the caller from the auth middleware to the upload handler. */
  type AuthedRequest = Request & {
    authCtx?: { user: NonNullable<Awaited<ReturnType<AuthService['verifyAndLoad']>>>; organizationId: string };
  };

  async function authenticate(req: Request): Promise<{ user: Awaited<ReturnType<AuthService['verifyAndLoad']>>; organizationId: string | null } | null> {
    const header = req.headers.authorization;
    const token = header?.startsWith('Bearer ') ? header.slice(7) : null;
    const user = token ? await authService.verifyAndLoad(token) : null;
    if (!user) return null;
    const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
    return { user, organizationId: org?.id ?? null };
  }

  // POST /api/uploads  (multipart: file, ownerType, ownerId, caption?, role?,
  //                     documentTypeId? — required when ownerType = PROPERTY or MAINTENANCE_REQUEST)
  router.post(
    '/',
    // Authenticate BEFORE multer: it buffers the whole body into memory, so an
    // anonymous caller could otherwise make the server hold 10 MB per request.
    (req: AuthedRequest, res, next) => {
      void authenticate(req).then((ctx) => {
        if (!ctx?.user || !ctx.organizationId) return res.status(401).json({ error: 'Unauthorized' });
        req.authCtx = { user: ctx.user, organizationId: ctx.organizationId };
        next();
      }, next);
    },
    (req, res, next) => upload.single('file')(req, res, (err: unknown) => (err ? sendError(res, err) : next())),
    async (req: AuthedRequest, res: Response) => {
      try {
        const ctx = req.authCtx!;
        const file = req.file;
        if (!file) return res.status(400).json({ error: 'No file provided' });
        const ownerType = String(req.body.ownerType ?? '');
        const ownerId = String(req.body.ownerId ?? '');
        if (!OWNER_TYPES.has(ownerType) || !ownerId) {
          return res.status(400).json({ error: 'Valid ownerType and ownerId are required' });
        }
        const att = await attachments.upload({
          user: ctx.user,
          organizationId: ctx.organizationId,
          ownerType: ownerType as AttachmentOwnerType,
          ownerId,
          filename: file.originalname,
          mimeType: file.mimetype,
          buffer: file.buffer,
          caption: req.body.caption ? String(req.body.caption) : null,
          role: req.body.role ? String(req.body.role) : null,
          documentTypeId: req.body.documentTypeId ? String(req.body.documentTypeId) : null,
        });
        return res.status(201).json({
          id: att.id,
          filename: att.filename,
          mimeType: att.mimeType,
          sizeBytes: att.sizeBytes,
          role: att.role,
          caption: att.caption,
          documentTypeId: att.documentTypeId,
          createdAt: att.createdAt,
        });
      } catch (err) {
        return sendError(res, err);
      }
    },
  );

  // DELETE /api/uploads/:id  → removes an attachment (authorised against its owner)
  router.delete('/:id', async (req: Request, res: Response) => {
    try {
      const ctx = await authenticate(req);
      if (!ctx?.user || !ctx.organizationId) return res.status(401).json({ error: 'Unauthorized' });
      await attachments.remove(ctx.user, ctx.organizationId, req.params.id as string);
      return res.status(204).end();
    } catch (err) {
      return sendError(res, err);
    }
  });

  // GET /api/uploads/:id  → streams the file to an authorised caller
  router.get('/:id', async (req: Request, res: Response) => {
    try {
      const ctx = await authenticate(req);
      if (!ctx?.user || !ctx.organizationId) return res.status(401).json({ error: 'Unauthorized' });
      const att = await attachments.getForDownload(ctx.user, ctx.organizationId, req.params.id as string);
      res.setHeader('Content-Type', att.mimeType);
      res.setHeader('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(att.filename)}`);
      res.setHeader('Content-Length', String(att.sizeBytes));
      res.setHeader('Cache-Control', 'private, no-store');
      res.setHeader('X-Content-Type-Options', 'nosniff');
      const stream = attachments.streamKey(att.storageKey);
      stream.on('error', () => {
        if (!res.headersSent) res.status(404).json({ error: 'File not found' });
      });
      stream.pipe(res);
    } catch (err) {
      return sendError(res, err);
    }
  });

  return router;
}

function sendError(res: Response, err: unknown): Response {
  if (err && typeof err === 'object' && 'code' in err && (err as { code: string }).code === 'LIMIT_FILE_SIZE') {
    return res.status(413).json({ error: 'File exceeds the 10MB limit' });
  }
  if (err instanceof HttpException) {
    return res.status(err.getStatus()).json({ error: err.message });
  }
  return res.status(500).json({ error: err instanceof Error ? err.message : 'Upload failed' });
}
