'use strict';

const authFlows = require('./flow-manager');

async function completeGoogleAuthFlow(flowId, gwsSetup, result, opts = {}) {
  const requestedEmail = opts.email || null;
  const requestedProfileId = opts.profileId || null;
  const email = requestedEmail || (result && result.email) || null;
  const profileId = (result && result.profileId) || requestedProfileId || null;
  if (!result || !result.success) {
    return authFlows.failAuthFlow(flowId, result && result.error ? result.error : 'OAuth failed', {
      principal: email,
      profileId,
      metadata: { email },
    });
  }
  if (!email) {
    return authFlows.failAuthFlow(flowId, 'OAuth completed, but CTM could not identify the Google account.', {
      profileId,
    });
  }
  try {
    const creds = await gwsSetup.getCredentials(email, profileId ? { profileId } : {});
    if (creds && creds.access_token) {
      let clearedAlerts = 0;
      try {
        const skillPlanner = opts.skillPlanner || require('../skills/skill-planner');
        const cleared = skillPlanner.clearResolvedGoogleWorkspaceHealthAlerts({
          email,
          profileId,
          authenticated: true,
        });
        clearedAlerts = cleared && cleared.cleared ? cleared.cleared : 0;
      } catch {}
      return authFlows.completeAuthFlow(flowId, {
        principal: email,
        profileId,
        metadata: { email, clearedAlerts },
      });
    }
    return authFlows.failAuthFlow(
      flowId,
      `OAuth completed, but ${email} is still not usable. Try reconnecting and choose the same Google account.`,
      { principal: email, profileId, metadata: { email } }
    );
  } catch (err) {
    return authFlows.failAuthFlow(flowId, err, {
      principal: email,
      profileId,
      metadata: { email },
    });
  }
}

async function verifySlackAuth(deps = {}) {
  const slackMcp = deps.slackMcp || require('../tools/slack-mcp');
  const slackOwner = deps.slackOwner || require('../tools/slack-owner');
  const skillPlanner = deps.skillPlanner || require('../skills/skill-planner');

  const authenticated = await slackMcp.isAuthenticated();
  const token = slackMcp.loadToken();
  if (!authenticated || !token || !token.access_token) {
    return {
      ok: false,
      error: 'Slack OAuth completed, but the saved token is not usable. Reconnect Slack and approve access again.',
    };
  }

  const repaired = slackOwner.repairSlackOwnerIdentity({ persist: true });
  if (!repaired.ok) {
    return {
      ok: false,
      error: repaired.error || 'Slack connected, but Wall-E could not identify the Slack owner account.',
      needsSlackAuth: !!repaired.needsSlackAuth,
    };
  }

  let clearedAlerts = 0;
  try {
    const cleared = skillPlanner.clearResolvedSlackHealthAlerts({
      authenticated: true,
      ownerConfigured: true,
    });
    clearedAlerts = cleared && cleared.cleared ? cleared.cleared : 0;
  } catch {}

  const userId = token.user_id || repaired.userId || null;
  return {
    ok: true,
    principal: userId,
    metadata: {
      user: userId,
      team: token.team_name || null,
      teamId: token.team_id || null,
      ownerConfigured: true,
      ownerSource: repaired.source || null,
      clearedAlerts,
    },
  };
}

async function completeSlackAuthFlow(flowId, deps = {}) {
  try {
    const verified = await verifySlackAuth(deps);
    if (!verified.ok) {
      return authFlows.failAuthFlow(flowId, verified.error || 'Slack authentication failed', {
        principal: verified.principal || null,
        metadata: verified.metadata || {},
      });
    }
    return authFlows.completeAuthFlow(flowId, {
      principal: verified.principal || null,
      metadata: verified.metadata || {},
    });
  } catch (err) {
    return authFlows.failAuthFlow(flowId, err);
  }
}

module.exports = {
  completeGoogleAuthFlow,
  verifySlackAuth,
  completeSlackAuthFlow,
};
