import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { PrismaService } from "src/prisma/prisma.service";
import { RequestUser } from "../types/request-user.type";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(private prisma: PrismaService, config: ConfigService) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: config.getOrThrow<string>('JWT_SECRET'),
        });
    }

    async validate(payload: { sub: string; email: string }): Promise<RequestUser | null> {
        // console.log('JwtStrategy: Validating JWT payload', payload);
        const user = await this.prisma.user.findUnique({
            where: { id: payload.sub },
            include: {
                role: true,
                branches: {
                    include: { branch: true },
                },
            },
        });

        if (!user) return null;

        // If role has access to all branches
        if (user.role?.accessAllBranch) {
            const allBranches = await this.prisma.branch.findMany();

            // normalize structure to match user.branches format
            user.branches = allBranches.map((branch) => ({
                branch,
                branchId: branch.id,
                userId: user.id,
            })) as any;
        }

        delete (user as any).hash;
        return user as RequestUser; // attached to req.user
    }
}