import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import { getUserById, findOrCreateUserByGoogle } from "../repositories/userRepository.js";

passport.serializeUser((user, done) => {
  done(null, user.user_id || user.id);
});

passport.deserializeUser(async (id, done) => {
  try {
    const user = await getUserById(id);
    if (!user) {
      return done(null, false);
    }
    done(null, user);
  } catch (error) {
    done(error, null);
  }
});

const hasGoogleServerOAuth =
  process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET;

if (hasGoogleServerOAuth) {
  passport.use(
    new GoogleStrategy(
      {
        clientID: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL:
          process.env.GOOGLE_CALLBACK_URL ||
          "/api/master/auth/google/callback",
      },
      async (accessToken, refreshToken, profile, done) => {
        try {
          const user = await findOrCreateUserByGoogle(profile);
          return done(null, user);
        } catch (error) {
          return done(error, null);
        }
      }
    )
  );
}

export default passport;
