import type { Middleware } from "koa";
import jwt from "koa-jwt";
import jwtConfig from "../config/jwt";

// JWT authentication middleware
export const authenticate: Middleware = jwt({
  secret: jwtConfig.secret,
}).unless({
  // Paths that don't require authentication
  path: [
    "/api/auth/login", 
    "/api/auth/register", 
    "/api/auth/register-admin",
    "/api/push/vapid-public-key"
  ],
});

// Error handling middleware for JWT authentication
export const handleJwtError: Middleware = async (ctx, next) => {
  try {
    // Next middleware have to be jwt call.
    await next();
  } catch (err: any) {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: "Unauthorized - Invalid or expired token",
      };
    } else {
      throw err;
    }
  }
};
