import express, { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requireFeature } from '../../middleware/requireFeature';
import { env } from '../../config/env';
import * as svc from './attachments.service';

/**
 * /api/attachments — files on a record. Any signed-in hostel user may call
 * it; the record's owner rule (attachments.service) decides each time.
 */
export const attachmentRouter = Router();
attachmentRouter.use(authenticate, requireFeature('attachments'));

const viewerOf = (req: Request): svc.Viewer => ({ userId: req.user!.sub, role: req.user!.role, perms: req.user!.perms });
const ownerSchema = z.object({ ownerType: z.string().trim().min(1).max(40), ownerId: z.string().uuid() });

attachmentRouter.get(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const { ownerType, ownerId } = ownerSchema.parse(req.query);
    res.json({ attachments: await svc.listAttachments(viewerOf(req), ownerType, ownerId) });
  }),
);

// The file is the raw body (as /api/uploads/direct); the record and the
// file's name ride the query string.
attachmentRouter.post(
  '/',
  express.raw({ type: () => true, limit: env.UPLOAD_MAX_BYTES + 1024 }),
  asyncHandler(async (req: Request, res: Response) => {
    const q = ownerSchema.extend({ name: z.string().trim().min(1).max(120) }).parse(req.query);
    const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
    const attachment = await svc.addAttachment(viewerOf(req), { ...q, contentType: req.header('content-type') ?? '', body });
    res.status(201).json({ attachment });
  }),
);

attachmentRouter.delete(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await svc.removeAttachment(viewerOf(req), z.string().uuid().parse(req.params.id)));
  }),
);
