import { openStore } from "@/lib/data/store";

/**
 * Signing in with an account someone already has.
 *
 * Each provider wants different endpoints and scopes, so they're described
 * here once and read by the callback too — two copies would disagree the
 * first time one was changed.
 */
export type ProviderName = "google" | "facebook" | "twitter" | "github";

export const PROVIDERS: Record<
  ProviderName,
  {
    label: string;
    authUrl: string;
    tokenUrl: string;
    profileUrl: string;
    scope: string;
    /** Which settings hold its keys. */
    idKey: string;
    secretKey: string;
  }
> = {
  google: {
    label: "Google",
    authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
    tokenUrl: "https://oauth2.googleapis.com/token",
    profileUrl: "https://www.googleapis.com/oauth2/v3/userinfo",
    scope: "openid email profile",
    idKey: "googleClientId",
    secretKey: "googleClientSecret",
  },
  facebook: {
    label: "Facebook",
    authUrl: "https://www.facebook.com/v18.0/dialog/oauth",
    tokenUrl: "https://graph.facebook.com/v18.0/oauth/access_token",
    profileUrl: "https://graph.facebook.com/me?fields=id,name,email",
    scope: "email public_profile",
    idKey: "facebookAppId",
    secretKey: "facebookAppSecret",
  },
  twitter: {
    label: "X",
    authUrl: "https://twitter.com/i/oauth2/authorize",
    tokenUrl: "https://api.twitter.com/2/oauth2/token",
    profileUrl: "https://api.twitter.com/2/users/me",
    scope: "tweet.read users.read",
    idKey: "twitterClientId",
    secretKey: "twitterClientSecret",
  },
  github: {
    label: "GitHub",
    authUrl: "https://github.com/login/oauth/authorize",
    tokenUrl: "https://github.com/login/oauth/access_token",
    profileUrl: "https://api.github.com/user",
    scope: "read:user user:email",
    idKey: "githubClientId",
    secretKey: "githubClientSecret",
  },
};

/**
 * A provider's keys, and where it should send people back to.
 *
 * The secret is read here, on the server, and never goes near the browser.
 */
export async function credentials(name: ProviderName) {
  const store = await openStore();
  const s = await store.settings();
  const config = PROVIDERS[name];

  return {
    id: String(s[config.idKey] ?? "").trim(),
    secret: String(s[config.secretKey] ?? "").trim(),
    siteUrl: String(s.siteUrl ?? "").replace(/\/$/, ""),
    enabled: s.socialLoginEnabled !== false,
  };
}
