import { Context, Next } from 'hono';
import { verify } from 'hono/jwt';
import { prisma } from '../utils/prisma';
import { config } from '../config';

export const authenticate = async (c: Context, next: Next) => {
  try {
    // Check for Bearer token
    const authHeader = c.req.header('Authorization');
    if (authHeader && authHeader.startsWith('Bearer ')) {
      const token = authHeader.substring(7);
      
      try {
        const payload = await verify(token, config.JWT_SECRET, 'HS256') as {
          sub: string;
          email: string;
          role: string;
        };
        
        c.set('userId', payload.sub);
        c.set('userRole', payload.role);
        c.set('authType', 'jwt');
        
        return next();
      } catch (error) {
        // Invalid JWT, continue to check API key
      }
    }
    
    // Check for API key
    const apiKey = c.req.header('X-API-Key');
    if (apiKey) {
      const user = await prisma.user.findUnique({
        where: { 
          apiKey,
          isActive: true,
        },
        select: {
          id: true,
          role: true,
        },
      });
      
      if (user) {
        c.set('userId', user.id);
        c.set('userRole', user.role);
        c.set('authType', 'apiKey');
        
        return next();
      }
    }
    
    return c.json({ error: 'Unauthorized' }, 401);
  } catch (error) {
    return c.json({ error: 'Authentication failed' }, 401);
  }
};

export const requireRole = (role: string) => {
  return async (c: Context, next: Next) => {
    const userRole = c.get('userRole');
    
    if (!userRole || userRole !== role) {
      return c.json({ error: 'Insufficient permissions' }, 403);
    }
    
    return next();
  };
};