import { createMiddleware } from 'hono/factory';
import type { UserRole } from '../types/index';

/**
 * Role hierarchy: owner > admin > operator > viewer > agent
 */
const ROLE_HIERARCHY: Record<UserRole, number> = {
  owner: 100,
  admin: 80,
  operator: 60,
  viewer: 20,
  agent: 40,
};

/**
 * Require a minimum role level
 */
export function requireRole(...allowedRoles: UserRole[]) {
  return createMiddleware(async (c, next) => {
    const auth = c.get('auth');
    if (!auth) {
      return c.json(
        { success: false, error: { code: 'UNAUTHORIZED', message: 'Not authenticated' } },
        401
      );
    }

    // Wildcard scope = full access
    if (auth.scopes.includes('*')) {
      return next();
    }

    if (!allowedRoles.includes(auth.role)) {
      return c.json(
        {
          success: false,
          error: {
            code: 'FORBIDDEN',
            message: `Role '${auth.role}' is not allowed. Required: ${allowedRoles.join(', ')}`,
          },
        },
        403
      );
    }

    return next();
  });
}

/**
 * Require specific scopes
 */
export function requireScope(...requiredScopes: string[]) {
  return createMiddleware(async (c, next) => {
    const auth = c.get('auth');
    if (!auth) {
      return c.json(
        { success: false, error: { code: 'UNAUTHORIZED', message: 'Not authenticated' } },
        401
      );
    }

    // Wildcard scope = full access
    if (auth.scopes.includes('*')) {
      return next();
    }

    const hasAll = requiredScopes.every((scope) => auth.scopes.includes(scope));
    if (!hasAll) {
      return c.json(
        {
          success: false,
          error: {
            code: 'FORBIDDEN',
            message: `Missing required scopes: ${requiredScopes.join(', ')}`,
          },
        },
        403
      );
    }

    return next();
  });
}
