/**
 * Locks the per-request isActive check in JwtStrategy.validate(). Ensures
 * admin-deactivated student/teacher sessions die immediately rather than
 * surviving until JWT expiry.
 */
import { UnauthorizedException } from '@nestjs/common';
import { JwtStrategy } from './jwt.strategy';
import { Role } from '../roles/role.enum';

describe('JwtStrategy.validate — session-level isActive enforcement', () => {
    function build(stub: { student?: any; teacher?: any }) {
        const config = { get: (k: string) => (k === 'JWT_SECRET' ? 'test-secret' : undefined) } as any;
        const students = { findByIdForAuth: jest.fn().mockResolvedValue(stub.student ?? null) } as any;
        const teachers = { findByIdForAuth: jest.fn().mockResolvedValue(stub.teacher ?? null) } as any;
        return { strategy: new JwtStrategy(config, students, teachers), students, teachers };
    }

    it('STUDENT — passes when isActive=true', async () => {
        const { strategy } = build({ student: { _id: 's1', isActive: true } });
        const out = await strategy.validate({ sub: 's1', email: 's@x.com', role: Role.STUDENT });
        expect(out).toEqual({ id: 's1', email: 's@x.com', role: Role.STUDENT });
    });

    it('STUDENT — throws 401 when isActive=false', async () => {
        const { strategy } = build({ student: { _id: 's1', isActive: false } });
        await expect(
            strategy.validate({ sub: 's1', email: 's@x.com', role: Role.STUDENT }),
        ).rejects.toThrow(UnauthorizedException);
    });

    it('STUDENT — throws 401 when student deleted (returns null)', async () => {
        const { strategy } = build({ student: null });
        await expect(
            strategy.validate({ sub: 'gone', email: 's@x.com', role: Role.STUDENT }),
        ).rejects.toThrow(UnauthorizedException);
    });

    it('STUDENT — legacy doc without isActive field treated as active', async () => {
        const { strategy } = build({ student: { _id: 's1' /* no isActive */ } });
        const out = await strategy.validate({ sub: 's1', email: 's@x.com', role: Role.STUDENT });
        expect(out.id).toBe('s1');
    });

    it('TEACHER — passes when isActive=true', async () => {
        const { strategy } = build({ teacher: { _id: 't1', isActive: true } });
        const out = await strategy.validate({ sub: 't1', email: 't@x.com', role: Role.TEACHER });
        expect(out).toEqual({ id: 't1', email: 't@x.com', role: Role.TEACHER });
    });

    it('TEACHER — throws 401 when isActive=false', async () => {
        const { strategy } = build({ teacher: { _id: 't1', isActive: false } });
        await expect(
            strategy.validate({ sub: 't1', email: 't@x.com', role: Role.TEACHER }),
        ).rejects.toThrow(UnauthorizedException);
    });

    it('ADMIN — passes without any DB lookup (admin has no isActive flag)', async () => {
        const { strategy, students, teachers } = build({});
        const out = await strategy.validate({ sub: 'a1', email: 'a@x.com', role: Role.ADMIN });
        expect(out).toEqual({ id: 'a1', email: 'a@x.com', role: Role.ADMIN });
        expect(students.findByIdForAuth).not.toHaveBeenCalled();
        expect(teachers.findByIdForAuth).not.toHaveBeenCalled();
    });

    it('Routes lookups to the correct service per role', async () => {
        const { strategy, students, teachers } = build({
            student: { _id: 's1', isActive: true },
            teacher: { _id: 't1', isActive: true },
        });
        await strategy.validate({ sub: 's1', email: 's@x.com', role: Role.STUDENT });
        expect(students.findByIdForAuth).toHaveBeenCalledWith('s1');
        expect(teachers.findByIdForAuth).not.toHaveBeenCalled();

        students.findByIdForAuth.mockClear();
        teachers.findByIdForAuth.mockClear();

        await strategy.validate({ sub: 't1', email: 't@x.com', role: Role.TEACHER });
        expect(teachers.findByIdForAuth).toHaveBeenCalledWith('t1');
        expect(students.findByIdForAuth).not.toHaveBeenCalled();
    });
});
