import express from "express";
import multer from "multer";
import path from "path";
import {
  login,
  createAdmin,
  verifySession,
  getCurrentUser,
  refreshToken,
  logout,
  getUsers,
  getUserById,
  confirmEmail,
  editUser,
  forgotPassword,
} from "../controllers/adminController";
import { authorizeModules, verifyToken } from "../middlewares/authJwt";
import { fileURLToPath } from "url";

const routes = express.Router();

// Configuración de almacenamiento
const storage = multer.diskStorage({
  destination: (req: any, file: any, cb: any) => {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    cb(null, path.join(__dirname, "../public/profile-pics"));
  },
  filename: (req: any, file: any, cb: any) => {
    const ext = path.extname(file.originalname);
    cb(null, `user-${Date.now()}${ext}`);
  },
});

// Filtros y límites
const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
  fileFilter: (req: any, file: any, cb: any) => {
    if (/^image\/(jpeg|png|gif)$/.test(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error("Solo JPG, PNG o GIF"));
    }
  },
});

routes.route("/login").post(login);
routes.route("/logout").post(logout);

routes.route("/users/confirm-email").post(confirmEmail);
routes.route("/users/forgot-password").post(forgotPassword);

routes.use(verifyToken);

routes.route("/verify-session").get(verifySession);
routes.route("/refresh-token").post(refreshToken);
routes.route("/current-user").get(getCurrentUser);

routes.use(authorizeModules("users"));
routes.route("/create").post(createAdmin);
routes.route("/users").get(getUsers);
routes
  .route("/users/:id")
  .get(getUserById)
  .patch(upload.single("profilePicture"), editUser);

export default routes;
