import UserModel from '../models/user'

function genericStrategy(provider) {
  return async (_accessToken, _refreshToken, profile, done) => {
    if (!profile.emails?.[0].value) {
      console.error(`${provider} Email permission not provided`)
      return done(null, false)
    }

    try {
      const user = await UserModel.findOne({ provider, providerId: profile.id }).exec()

      console.info(`${provider} user found. Logging in.`)

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

      console.info(`${provider} user not found. Creating.`)

      const newUser = new UserModel({
        providerId: profile.id,
        name: profile.displayName,
        provider,
        email: profile.emails?.[0].value,
        photo: profile.photos?.[0].value.replace('_normal', '').replace('=s96-c', ''),
      }).save((err) => {
        if (err) throw err
      })

      return done(null, newUser)
    } catch (e) {
      return done(e)
    }
  }
}

export default genericStrategy
