const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

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

// Deserialize user from session
passport.deserializeUser(async (id, done) => {
  try {
    const { getUserById } = require('../repositories/userRepository');
    const user = await getUserById(id);
    if (!user) {
      return done(null, false);
    }
    done(null, user);
  } catch (error) {
    done(error, null);
  }
});

// Google OAuth (redirect flow) — only register when server-side OAuth credentials exist
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/sat/auth/google/callback',
      },
      async (accessToken, refreshToken, profile, done) => {
        try {
          const { findOrCreateUserByGoogle } = require('../repositories/userRepository');
          const user = await findOrCreateUserByGoogle(profile);
          return done(null, user);
        } catch (error) {
          return done(error, null);
        }
      }
    )
  );
} else {
  console.warn(
    '[passport] Google OAuth redirect disabled: set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in SAT_backend/.env. Google Sign-In (ID token) and password login still work if configured.'
  );
}

module.exports = passport;
