import express, { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { presignStudentUpload, presignDownload, uploadDirect } from './uploads.service';
import { env } from '../../config/env';
import { ForbiddenError } from '../../lib/errors';

const presignSchema = z.object({
  kind: z.enum(['ID_PROOF', 'PHOTO', 'PROPERTY_LOGO', 'BILLING_LOGO', 'ADDRESS_PROOF', 'POLICE_VERIFICATION', 'ASSET_PHOTO', 'VISITOR_PHOTO', 'PROPERTY_PHOTO']),
  contentType: z.string().min(1),
  contentLength: z.coerce.number().int().positive(),
});

export const uploadRouter = Router();
uploadRouter.use(authenticate);

// Staff upload everything; a student may only upload their own photo, and
// nothing else — the rest is paperwork the warden verifies and files.
//
// MESS_ADMIN is included: every staff role may replace its own profile photo,
// and leaving it out refused the picker with a 403 before anything could be
// saved. What any of them may presign is still bounded — the key is built
// server-side from their tenant. SUPER_ADMIN stays out, having no tenant to
// scope a key to.
const staffOnly = authorize(Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN);

uploadRouter.post(
  '/presign',
  staffOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const input = presignSchema.parse(req.body);
    const result = await presignStudentUpload({ tenantId: req.user!.tenantId!, ...input });
    res.json(result);
  }),
);

// A read url for a file this tenant uploaded — the invoice logo, a student's
// photo. Same roles that can upload.
uploadRouter.get(
  '/file-url',
  staffOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const key = z.string().min(1).max(500).parse(req.query.key);
    res.json({ url: await presignDownload(req.user!.tenantId!, key) });
  }),
);

// The upload itself, relayed through the API. express.raw captures the body
// as a Buffer; the limit mirrors the service's own check so an oversized file
// is refused at the door rather than buffered first.
uploadRouter.post(
  '/direct',
  express.raw({ type: () => true, limit: env.UPLOAD_MAX_BYTES + 1024 }),
  asyncHandler(async (req: Request, res: Response) => {
    const kind = z.enum(['ID_PROOF', 'PHOTO', 'PROPERTY_LOGO', 'BILLING_LOGO', 'ADDRESS_PROOF', 'POLICE_VERIFICATION', 'ASSET_PHOTO', 'VISITOR_PHOTO', 'PROPERTY_PHOTO']).parse(req.query.kind);
    if (req.user!.role === Role.STUDENT) {
      if (kind !== 'PHOTO') throw new ForbiddenError('Students may only upload a profile photo');
    } else if (
      req.user!.role !== Role.HOSTEL_ADMIN &&
      req.user!.role !== Role.WARDEN &&
      req.user!.role !== Role.MESS_ADMIN
    ) {
      throw new ForbiddenError('You do not have permission to upload files');
    }
    const contentType = req.header('content-type') ?? '';
    const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
    res.status(201).json(await uploadDirect({ tenantId: req.user!.tenantId!, kind, contentType, body }));
  }),
);
