const passport = require('passport');
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
const jwt = require('jsonwebtoken');
const db = require('../db');

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: process.env.GOOGLE_CALLBACK_URL,
    },
    async (_accessToken, _refreshToken, profile, done) => {
      try {
        const user = await db.user.upsert({
          where: { googleId: profile.id },
          update: {
            email: profile.emails[0].value,
            displayName: profile.displayName,
            avatarUrl: profile.photos?.[0]?.value ?? null,
          },
          create: {
            googleId: profile.id,
            email: profile.emails[0].value,
            displayName: profile.displayName,
            avatarUrl: profile.photos?.[0]?.value ?? null,
          },
        });

        const token = jwt.sign(
          {
            userId: user.id,
            email: user.email,
            name: user.displayName,
            picture: user.avatarUrl,
          },
          process.env.JWT_SECRET,
          { algorithm: 'HS256', expiresIn: '7d' }
        );

        done(null, { token });
      } catch (err) {
        done(err);
      }
    }
  )
);

module.exports = passport;
