import Facebook, {
  type FacebookProfile,
} from "next-auth/providers/facebook";

export const FACEBOOK_AUTHORIZATION_SCOPE = "public_profile";
export const FACEBOOK_PROFILE_FIELDS = "id,name,picture.type(large)";

export function createFacebookProvider() {
  return Facebook({
    clientId: process.env.AUTH_FACEBOOK_ID ?? "",
    clientSecret: process.env.AUTH_FACEBOOK_SECRET ?? "",
    authorization: {
      params: { scope: FACEBOOK_AUTHORIZATION_SCOPE },
    },
    userinfo: {
      params: { fields: FACEBOOK_PROFILE_FIELDS },
    },
    profile: mapFacebookProfile,
  });
}

export function mapFacebookProfile(profile: FacebookProfile) {
  return {
    id: profile.id,
    name: typeof profile.name === "string" ? profile.name : null,
    email: null,
    image:
      typeof profile.picture?.data?.url === "string"
        ? profile.picture.data.url
        : null,
  };
}
