import jwt from 'jsonwebtoken';
import { TokenPayload } from '../../types/auth.types.js';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRE = process.env.JWT_EXPIRE || '7d';

// Generate JWT token
export const generateToken = (user: any): string => {
    const payload: TokenPayload = {
        userId: user.id,
        email: user.email,
        role: user.roleCode,
        locationId: user.locationId,
        districtId: user.districtId
    };

    return jwt.sign(payload, JWT_SECRET, {
        expiresIn: JWT_EXPIRE as any
    });
};

// Verify JWT token
export const verifyToken = (token: string): TokenPayload => {
    try {
        return jwt.verify(token, JWT_SECRET) as TokenPayload;
    } catch (error) {
        throw new Error('Invalid or expired token');
    }
};

export { JWT_SECRET };
