import { Injectable } from "@nestjs/common";
import { PassportSerializer } from "@nestjs/passport";
import { UsersService } from "../users/users.service";
import { SafeUser } from "./auth.service";

@Injectable()
export class SessionSerializer extends PassportSerializer {
  constructor(private readonly usersService: UsersService) {
    super();
  }

  serializeUser(user: SafeUser, done: (err: Error | null, id: string) => void) {
    done(null, user.id);
  }

  async deserializeUser(id: string, done: (err: Error | null, user: SafeUser | null) => void) {
    const user = await this.usersService.findById(id);
    if (!user) {
      done(null, null);
      return;
    }
    const { passwordHash: _passwordHash, ...safeUser } = user;
    done(null, safeUser);
  }
}
