import { ExecutionContext, Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Request } from "express";

/**
 * Validates credentials via LocalStrategy AND establishes the session:
 * super.logIn(request) calls passport's req.login, which serializes the user
 * into the session store so subsequent requests carry an authenticated
 * session cookie (otherwise login succeeds but no session is persisted).
 */
@Injectable()
export class LocalAuthGuard extends AuthGuard("local") {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const result = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest<Request>();
    await super.logIn(request);
    return result;
  }
}
