import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import User from '../models/User';
import { resolveGoogleOAuthCallbackUrl } from '../utils/googleOAuthCallbackUrl';

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

const isConfigured =
  GOOGLE_CLIENT_ID &&
  GOOGLE_CLIENT_ID !== 'your_google_client_id' &&
  GOOGLE_CLIENT_SECRET &&
  GOOGLE_CLIENT_SECRET !== 'your_google_client_secret';

if (isConfigured) {
  const googleCallbackURL = resolveGoogleOAuthCallbackUrl();
  const hasPublicOAuthOrigin =
    !!process.env.GOOGLE_CALLBACK_URL?.trim() ||
    !!process.env.API_PUBLIC_URL?.trim() ||
    (!!process.env.HOST_PRODUCTION?.trim() && process.env.NODE_ENV === 'production') ||
    !!process.env.BASE_URL?.trim();

  console.log(
    '[Google OAuth] Passport callbackURL (must match Google Cloud redirect URI):',
    googleCallbackURL
  );
  if (!hasPublicOAuthOrigin && process.env.NODE_ENV === 'production') {
    console.warn(
      '[Google OAuth] Set GOOGLE_CALLBACK_URL (or API_PUBLIC_URL / HOST_PRODUCTION in production / BASE_URL) so redirect_uri matches Google Cloud Console.'
    );
  }
  if (
    process.env.NODE_ENV === 'production' &&
    googleCallbackURL.includes('localhost')
  ) {
    console.warn(
      '[Google OAuth] callbackURL still points at localhost in production — Google will return redirect_uri_mismatch unless that exact URI is registered. Set GOOGLE_CALLBACK_URL to your public API, e.g. https://api.quickconnectnow.co:5513/api/auth/google/callback'
    );
  }

  passport.use(
    new GoogleStrategy(
      {
        clientID: GOOGLE_CLIENT_ID!,
        clientSecret: GOOGLE_CLIENT_SECRET!,
        callbackURL: googleCallbackURL,
        passReqToCallback: true,
      },
      async (req, accessToken, refreshToken, profile, done) => {
        try {
          // Check if user already exists by googleId
          let user = await User.findOne({ googleId: profile.id });

          if (user) {
            return done(null, user);
          }

          // Check if user exists by email
          const email = profile.emails?.[0].value;
          if (email) {
            user = await User.findOne({ email });
            if (user) {
              // Update user with googleId
              user.googleId = profile.id;
              await user.save();
              return done(null, user);
            }
          }

          // Create new user if doesn't exist
          user = await User.create({
            googleId: profile.id,
            email: email,
            first_name: profile.name?.givenName || profile.displayName,
            last_name: profile.name?.familyName || '',
            profile_picture: profile.photos?.[0].value,
            status: 'ACTIVE',
            // First Google sign-in should complete CreateProfile; set true in create-profile API.
            isProfileComplete: false,
          });

          return done(null, user);
        } catch (error) {
          return done(error as Error, undefined);
        }
      }
    )
  );
} else {
  console.warn('Google OAuth credentials missing. Google login will not work.');
}

passport.serializeUser((user: any, done) => {
  done(null, {
    userId: user._id.toString(),
    email: user.email,
    role: user.role,
  });
});

passport.deserializeUser((user: any, done) => {
  done(null, user);
});

export default passport;
