import { Router } from 'express';
import { Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import * as ctrl from './tenant.controller';
import * as svc from './tenant.service';
import { tenantOverview } from './tenant-overview.service';
import { clockOf, extendTrial, renewPlan } from './tenant-access.service';
import { extendTrialSchema, renewSchema } from './tenant.schemas';
import { z } from 'zod';

export const tenantRouter = Router();

// All tenant management is SUPER_ADMIN only.
tenantRouter.use(authenticate, authorize(Role.SUPER_ADMIN));

// Deletion requests raised by hostel admins. Declared before '/:id' so the
// literal path is not swallowed by the parameter.
tenantRouter.get(
  '/deletion-requests',
  asyncHandler(async (_req, res) => res.json({ requests: await svc.listDeletionRequests() })),
);
tenantRouter.post(
  '/deletion-requests/:id/approve',
  asyncHandler(async (req, res) => {
    const { confirmName, note } = z.object({ confirmName: z.string().min(1), note: z.string().max(300).optional() }).parse(req.body);
    res.json(await svc.approveDeletionRequest(req.params.id, confirmName, req.user!.sub, note));
  }),
);
tenantRouter.post(
  '/deletion-requests/:id/reject',
  asyncHandler(async (req, res) => {
    const { note } = z.object({ note: z.string().max(300).optional() }).parse(req.body);
    res.json({ request: await svc.rejectDeletionRequest(req.params.id, req.user!.sub, note) });
  }),
);

tenantRouter.post('/', asyncHandler(ctrl.createTenant));
tenantRouter.get('/', asyncHandler(ctrl.listTenants));
tenantRouter.get('/:id', asyncHandler(ctrl.getTenant));
// The tenant page: account, access, KPIs, properties, people, plan, billing, setup.
tenantRouter.get('/:id/overview', asyncHandler(async (req, res) => res.json({ overview: await tenantOverview(req.params.id) })));
/** Renew or change the paid plan; reactivates a hostel that had run out. */
tenantRouter.post(
  '/:id/renew',
  asyncHandler(async (req, res) => res.json(await renewPlan(req.params.id, renewSchema.parse(req.body), req.user!.sub, clockOf(req.headers)))),
);
/** More trial days; reactivates a hostel whose trial had run out. */
tenantRouter.post(
  '/:id/extend-trial',
  asyncHandler(async (req, res) => res.json(await extendTrial(req.params.id, extendTrialSchema.parse(req.body).days, clockOf(req.headers)))),
);
tenantRouter.patch('/:id', asyncHandler(ctrl.updateTenant));
tenantRouter.patch('/:id/plan', asyncHandler(ctrl.setPlan));
tenantRouter.post('/:id/suspend', asyncHandler(ctrl.suspendTenant));
tenantRouter.post('/:id/activate', asyncHandler(ctrl.activateTenant));
tenantRouter.delete('/:id', asyncHandler(ctrl.deleteTenant));
