import { Router } from "express";
import {
  changePassword,
  getCurrentUser,
  loginStaff,
  logout,
  logoutAll,
  refreshAuthToken,
  registerStaff,
  requestCustomerOtp,
  requestStaffOtp,
  updateCustomerProfile,
  verifyCustomerOtp,
  verifyStaffOtp,
} from "../controllers/authController.js";
import { optionalAuth, requireAuth } from "../middleware/authMiddleware.js";
import { rateLimit } from "../middleware/rateLimit.js";
import { validateBody } from "../middleware/validateRequest.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import {
  changePasswordSchema,
  customerRequestOtpSchema,
  customerUpdateProfileSchema,
  customerVerifyOtpSchema,
  logoutSchema,
  refreshTokenSchema,
  staffLoginSchema,
  staffRegisterSchema,
  staffRequestOtpSchema,
  staffVerifyOtpSchema,
} from "../validators/authValidators.js";

const router = Router();

const otpLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5,
  keyPrefix: "otp",
});
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 10,
  keyPrefix: "login",
});

router.post(
  "/customer/request-otp",
  otpLimiter,
  validateBody(customerRequestOtpSchema),
  asyncHandler(requestCustomerOtp),
);

router.post(
  "/customer/verify-otp",
  otpLimiter,
  validateBody(customerVerifyOtpSchema),
  asyncHandler(verifyCustomerOtp),
);

router.post(
  "/staff/register",
  optionalAuth,
  loginLimiter,
  validateBody(staffRegisterSchema),
  asyncHandler(registerStaff),
);

router.post(
  "/staff/login",
  loginLimiter,
  validateBody(staffLoginSchema),
  asyncHandler(loginStaff),
);

router.post(
  "/staff/request-otp",
  otpLimiter,
  validateBody(staffRequestOtpSchema),
  asyncHandler(requestStaffOtp),
);

router.post(
  "/staff/verify-otp",
  otpLimiter,
  validateBody(staffVerifyOtpSchema),
  asyncHandler(verifyStaffOtp),
);

router.post(
  "/refresh",
  loginLimiter,
  validateBody(refreshTokenSchema),
  asyncHandler(refreshAuthToken),
);

router.post("/logout", validateBody(logoutSchema), asyncHandler(logout));

router.post(
  "/change-password",
  requireAuth,
  validateBody(changePasswordSchema),
  asyncHandler(changePassword),
);

router.post("/logout-all", requireAuth, asyncHandler(logoutAll));

router.patch(
  "/customer/profile",
  requireAuth,
  validateBody(customerUpdateProfileSchema),
  asyncHandler(updateCustomerProfile),
);

router.get("/me", requireAuth, asyncHandler(getCurrentUser));

export default router;
