import { aQ as useRuntimeConfig } from '../nitro/nitro.mjs';

const oauthConfigs = {
  google: (config) => {
    const cfg = config;
    return {
      clientId: cfg.oauth.google.clientId,
      clientSecret: cfg.oauth.google.clientSecret,
      authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
      tokenUrl: "https://oauth2.googleapis.com/token",
      userInfoUrl: "https://www.googleapis.com/oauth2/v2/userinfo",
      scope: ["openid", "email", "profile"]
    };
  },
  github: (config) => {
    const cfg = config;
    return {
      clientId: cfg.oauth.github.clientId,
      clientSecret: cfg.oauth.github.clientSecret,
      authorizeUrl: "https://github.com/login/oauth/authorize",
      tokenUrl: "https://github.com/login/oauth/access_token",
      userInfoUrl: "https://api.github.com/user",
      scope: ["user:email"]
    };
  },
  facebook: (config) => {
    const cfg = config;
    return {
      clientId: cfg.oauth.facebook.appId,
      clientSecret: cfg.oauth.facebook.appSecret,
      authorizeUrl: "https://www.facebook.com/v18.0/dialog/oauth",
      tokenUrl: "https://graph.facebook.com/v18.0/oauth/access_token",
      userInfoUrl: "https://graph.facebook.com/me?fields=id,name,email,picture",
      scope: ["email", "public_profile"]
    };
  },
  vk: (config) => {
    const cfg = config;
    return {
      clientId: cfg.oauth.vk.appId,
      clientSecret: cfg.oauth.vk.appSecret,
      authorizeUrl: "https://oauth.vk.com/authorize",
      tokenUrl: "https://oauth.vk.com/access_token",
      userInfoUrl: "https://api.vk.com/method/users.get",
      scope: ["email"]
    };
  }
};
function getOAuthConfig(provider) {
  const runtimeConfig = useRuntimeConfig();
  const configFn = oauthConfigs[provider];
  if (!configFn) {
    throw new Error(`OAuth provider '${provider}' is not supported`);
  }
  const config = configFn(runtimeConfig);
  if (!config.clientId || !config.clientSecret) {
    throw new Error(`OAuth provider '${provider}' is not configured. Please set credentials in .env`);
  }
  return config;
}
function generateAuthUrl(provider, redirectUri, state) {
  const config = getOAuthConfig(provider);
  const params = new URLSearchParams({
    client_id: config.clientId,
    redirect_uri: redirectUri,
    response_type: "code",
    scope: config.scope.join(" "),
    ...state
  });
  return `${config.authorizeUrl}?${params.toString()}`;
}
async function exchangeCodeForToken(provider, code, redirectUri) {
  const config = getOAuthConfig(provider);
  const body = new URLSearchParams({
    client_id: config.clientId,
    client_secret: config.clientSecret,
    code,
    redirect_uri: redirectUri,
    grant_type: "authorization_code"
  });
  const response = await fetch(config.tokenUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Accept": "application/json"
    },
    body: body.toString()
  });
  if (!response.ok) {
    const error = await response.text();
    throw new Error(`Failed to exchange code for token: ${error}`);
  }
  const data = await response.json();
  return data.access_token;
}
async function getOAuthUserInfo(provider, accessToken) {
  var _a, _b, _c;
  const config = getOAuthConfig(provider);
  const response = await fetch(config.userInfoUrl, {
    headers: {
      "Authorization": `Bearer ${accessToken}`,
      "Accept": "application/json"
    }
  });
  if (!response.ok) {
    const error = await response.text();
    throw new Error(`Failed to get user info: ${error}`);
  }
  const data = await response.json();
  switch (provider) {
    case "google":
      return {
        id: data.id,
        email: data.email,
        name: data.name,
        picture: data.picture,
        provider
      };
    case "github":
      let email = data.email;
      if (!email) {
        const emailResponse = await fetch("https://api.github.com/user/emails", {
          headers: {
            "Authorization": `Bearer ${accessToken}`,
            "Accept": "application/json"
          }
        });
        if (emailResponse.ok) {
          const emails = await emailResponse.json();
          const primaryEmail = emails.find((e) => e.primary);
          email = (primaryEmail == null ? void 0 : primaryEmail.email) || ((_a = emails[0]) == null ? void 0 : _a.email);
        }
      }
      return {
        id: String(data.id),
        email: email || `${data.login}@github-oauth.local`,
        name: data.name || data.login,
        picture: data.avatar_url,
        provider
      };
    case "facebook":
      return {
        id: data.id,
        email: data.email,
        name: data.name,
        picture: (_b = data.picture) == null ? void 0 : _b.data,
        provider
      };
    case "vk":
      const vkApiVersion = "5.131";
      const vkUserInfoUrl = `${config.userInfoUrl}?fields=photo_200&access_token=${accessToken}&v=${vkApiVersion}`;
      const vkResponse = await fetch(vkUserInfoUrl);
      if (!vkResponse.ok) {
        throw new Error("Failed to get VK user info");
      }
      const vkData = await vkResponse.json();
      const vkUser = (_c = vkData.response) == null ? void 0 : _c[0];
      return {
        id: String(vkUser.id),
        email: data.email || `vk${vkUser.id}@vk-oauth.local`,
        name: `${vkUser.first_name} ${vkUser.last_name}`,
        picture: vkUser.photo_200,
        provider
      };
    default:
      throw new Error(`Unsupported provider: ${provider}`);
  }
}
function isValidProvider(provider) {
  return ["google", "github", "facebook", "vk"].includes(provider);
}

export { generateAuthUrl as a, exchangeCodeForToken as e, getOAuthUserInfo as g, isValidProvider as i };
//# sourceMappingURL=oauth.mjs.map
