import { Context, Next } from 'hono';
import { jwtVerify } from 'jose';
import { getStaffUserById } from '@/src/dbService';
import { ApiError } from '@/src/lib/api-error';
import { getEncodedJwtSecret } from '@/src/lib/env-exporter';

/**
 * Verify JWT token and extract payload
 */
const verifyStaffToken = async (token: string) => {
  try {
    const { payload } = await jwtVerify(token, getEncodedJwtSecret());
    return payload;
  } catch (error) {
    throw new ApiError('Access denied. Invalid auth credentials', 401);
  }
};

/**
 * Middleware to authenticate staff users and attach staffUser to context
 */
export const authenticateStaff = async (c: Context, next: Next) => {
  try {
    // Extract token from Authorization header
    const authHeader = c.req.header('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw new ApiError('Staff authentication required', 401);
    }

    const token = authHeader.split(' ')[1];

    if (!token) {
      throw new ApiError('Staff authentication token missing', 401);
    }

    // Verify token and extract payload
    const decoded = await verifyStaffToken(token) as any;

    // Verify staffId exists in token
    if (!decoded.staffId) {
      throw new ApiError('Invalid staff token format', 401);
    }

    /*
    // Old implementation - direct DB queries:
    import { db } from '@/src/db/db_index'
    import { staffUsers } from '@/src/db/schema'
    import { eq } from 'drizzle-orm';

    const staff = await db.query.staffUsers.findFirst({
      where: eq(staffUsers.id, decoded.staffId),
    });
    */

    // Fetch staff user from database
    const staff = await getStaffUserById(decoded.staffId);

    if (!staff) {
      throw new ApiError('Staff user not found', 401);
    }

    // Attach staff user to context
    c.set('staffUser', {
      id: staff.id,
      name: staff.name,
    });

    await next();
  } catch (error) {
    throw error;
  }
};
