import passport from 'passport';
import { Strategy as JwtStrategy } from 'passport-jwt';
import { Strategy as GoogleStrategy } from 'passport-google-oauth2';
import { Strategy as MicrosoftStrategy } from 'passport-microsoft';
import type { Request } from 'express';
import config from '@/shared/config';
import db from '@/db/models';
import UsersDBApi from '@/db/api/users';
import cookies from '@/auth/cookies';

const providers = config.providers;

interface JwtPayload {
  user: { email: string };
}

type VerifyDone = (error: unknown, user?: unknown) => void;

passport.use(
  new JwtStrategy(
    {
      passReqToCallback: true,
      secretOrKey: config.secret_key,
      jwtFromRequest: cookies.extractAccessCookie,
    },
    async (req: Request, token: JwtPayload, done: VerifyDone) => {
      try {
        const user = await UsersDBApi.findBy({ email: token.user.email });

        if (user && user.disabled) {
          return done(new Error(`User '${user.email}' is disabled`));
        }

        req.currentUser = user ?? undefined;

        return done(null, user);
      } catch (error) {
        done(error);
      }
    },
  ),
);

function socialStrategy(
  email: string,
  _profile: unknown,
  provider: string,
  done: VerifyDone,
): void {
  db.users
    .findOrCreate({ where: { email, provider } })
    .then(([user]) => done(null, { user }))
    .catch((error: unknown) => done(error));
}

if (config.google.clientId && config.google.clientSecret) {
  passport.use(
    new GoogleStrategy(
      {
        clientID: config.google.clientId,
        clientSecret: config.google.clientSecret,
        callbackURL: config.apiUrl + '/auth/signin/google/callback',
        passReqToCallback: true,
      },
      (_request, _accessToken, _refreshToken, profile, done) => {
        socialStrategy(profile.email ?? '', profile, providers.GOOGLE, done);
      },
    ),
  );
}

if (config.microsoft.clientId && config.microsoft.clientSecret) {
  passport.use(
    new MicrosoftStrategy(
      {
        clientID: config.microsoft.clientId,
        clientSecret: config.microsoft.clientSecret,
        callbackURL: config.apiUrl + '/auth/signin/microsoft/callback',
        passReqToCallback: true,
      },
      (_request, _accessToken, _refreshToken, profile, done) => {
        const email = profile._json.mail || profile._json.userPrincipalName || '';
        socialStrategy(email, profile, providers.MICROSOFT, done);
      },
    ),
  );
}
