import trim from 'lodash/trim';
import { create, Draft } from 'mutative';
import {
  type Account as AccountEntity,
  applicationSchema,
  instanceSchema,
  PlApiClient,
  tokenSchema,
  type CredentialAccount,
  type CredentialApplication,
  type Token,
} from 'pl-api';
import * as v from 'valibot';

import {
  decodeFromMarkup,
  MASTODON_PRELOAD_IMPORT,
  pleromaDecoder,
  type PreloadAction,
} from '@/actions/preload';
import * as BuildConfig from '@/build-config';
import { coerceObject } from '@/schemas/utils';
import KVStore from '@/storage/kv-store';
import { validId, isURL, parseBaseURL } from '@/utils/auth';

import {
  AUTH_APP_CREATED,
  AUTH_LOGGED_IN,
  AUTH_APP_AUTHORIZED,
  AUTH_LOGGED_OUT,
  SWITCH_ACCOUNT,
  VERIFY_CREDENTIALS_SUCCESS,
  VERIFY_CREDENTIALS_FAIL,
  type AuthAction,
} from '../actions/auth';
import { ME_FETCH_SKIP, type MeAction } from '../actions/me';

import type { PlfeResponse } from '@/api';

const instance = (() => {
  try {
    const preloadedInstance = decodeFromMarkup('initial-results', pleromaDecoder)[
      '/api/v1/instance'
    ];
    const parsedInstance = v.safeParse(instanceSchema, preloadedInstance);
    return parsedInstance.success ? parsedInstance.output : undefined;
  } catch (e) {
    return undefined;
  }
})();

type Action = AuthAction | MeAction | PreloadAction;

const backendUrl = isURL(BuildConfig.BACKEND_URL) ? BuildConfig.BACKEND_URL : '';

const mastodonPreloadSchema = coerceObject({
  meta: coerceObject({
    access_token: v.string(),
    me: v.string(),
  }),
  accounts: v.record(
    v.string(),
    v.object({
      url: v.string(),
    }),
  ),
});

const authUserSchema = v.object({
  access_token: v.string(),
  id: v.string(),
  url: v.string(),
});

const tokenWithAppSchema = v.object({
  ...tokenSchema.entries,
  client_id: v.fallback(v.optional(v.string()), undefined),
  client_secret: v.fallback(v.optional(v.string()), undefined),
});

type TokenWithApp = v.InferOutput<typeof tokenWithAppSchema>;

interface AuthUser {
  access_token: string;
  id: string;
  url: string;
}

interface State {
  app: CredentialApplication | null;
  tokens: Record<string, TokenWithApp>;
  users: Record<string, AuthUser>;
  me: string | null;
  client: InstanceType<typeof PlApiClient>;
}

const buildKey = (parts: string[]) => parts.join(':');

// For subdirectory support
const NAMESPACE = trim(BuildConfig.FE_SUBDIRECTORY, '/')
  ? `pl-fe@${BuildConfig.FE_SUBDIRECTORY}`
  : 'pl-fe';

const STORAGE_KEY = buildKey([NAMESPACE, 'auth']);

const getLocalState = (): State | undefined => {
  const state = JSON.parse(localStorage.getItem(STORAGE_KEY)!);

  if (!state) return undefined;

  return {
    app: state.app && v.parse(applicationSchema, state.app),
    tokens: Object.fromEntries(
      Object.entries(state.tokens).map(([key, value]) => [key, v.parse(tokenWithAppSchema, value)]),
    ),
    users: Object.fromEntries(
      Object.entries(state.users).map(([key, value]) => [key, v.parse(authUserSchema, value)]),
    ),
    me: state.me,
    client: new PlApiClient(
      parseBaseURL(state.me) || backendUrl,
      state.users[state.me]?.access_token,
      {
        instance,
      },
    ),
  };
};

const localState = getLocalState();

// Checks if the user has an ID and access token
const validUser = (user?: AuthUser) => {
  try {
    return !!(user && validId(user.id) && validId(user.access_token));
  } catch (e) {
    return false;
  }
};

// Finds the first valid user in the state
const firstValidUser = (state: State | Draft<State>) => Object.values(state.users).find(validUser);

// For legacy purposes. IDs get upgraded to URLs further down.
const getUrlOrId = (user?: AuthUser): string | null => {
  try {
    if (!user) return null;
    const { id, url } = user;
    return url || id;
  } catch {
    return null;
  }
};

// If `me` doesn't match an existing user, attempt to shift it.
const maybeShiftMe = (state: State | Draft<State>) => {
  const me = state.me!;
  const user = state.users[me];

  if (validUser(user)) {
    return state;
  }

  const nextUser = firstValidUser(state);
  state.me = getUrlOrId(nextUser);
};

// Set the user from the session or localStorage, whichever is valid first
const setSessionUser = (state: State) => {
  const user = state.users[state.me!];
  const me = getUrlOrId(validUser(user) ? user : undefined);

  state.me = me;
};

const isUpgradingUrlId = (state: State) => {
  const me = state.me;
  const user = state.users[me!];
  return validId(me) && user && !isURL(me);
};

// Checks the state and makes it valid
const sanitizeState = (state: State) => {
  // Skip sanitation during ID to URL upgrade
  if (isUpgradingUrlId(state)) return state;

  state.users = Object.fromEntries(
    Object.entries(state.users).filter(([url, user]) => validUser(user) && user.url === url),
  );
  // Remove mismatched tokens
  state.tokens = Object.fromEntries(
    Object.entries(state.tokens).filter(([id, token]) => validId(id) && token.access_token === id),
  );
};

const persistAuth = (state: State) => {
  const { client, ...data } = state;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
};

const persistState = (state: State) => {
  persistAuth(state);
};

const initialize = (state: State) => {
  maybeShiftMe(state);
  setSessionUser(state);
  sanitizeState(state);
  persistState(state);

  return state;
};

const initialState: State = initialize({
  app: null,
  tokens: {},
  users: {},
  me: null,
  client: new PlApiClient(backendUrl, undefined, { instance }),
  ...localState,
});

const importToken = (state: State | Draft<State>, token: Token, app?: CredentialApplication) => {
  state.tokens[token.access_token] = {
    client_id: app?.client_id,
    client_secret: app?.client_secret,
    ...token,
  };
};

// Users are now stored by their ActivityPub ID instead of their
// primary key to support auth against multiple hosts.
const upgradeNonUrlId = (state: State | Draft<State>, account: CredentialAccount) => {
  const me = state.me;
  if (isURL(me)) return state;

  state.me = state.me === account.id ? account.url : state.me;
  delete state.users[account.id];
};

// Returns a predicate function for filtering a mismatched user/token
const userMismatch =
  (token: string, account: CredentialAccount) => (user: AuthUser, url: string) => {
    const sameToken = user.access_token === token;
    const differentUrl = url !== account.url || user.url !== account.url;
    const differentId = user.id !== account.id;

    return sameToken && (differentUrl || differentId);
  };

const importCredentials = (
  state: State | Draft<State>,
  token: string,
  account: CredentialAccount,
) => {
  state.users[account.url] = v.parse(authUserSchema, {
    id: account.id,
    access_token: token,
    url: account.url,
  });
  // state.tokens[token].account = account.id;
  state.tokens[token].me = account.url;
  state.users = Object.fromEntries(
    Object.entries(state.users).filter(([url, user]) => !userMismatch(token, account)(user, url)),
  );
  state.me = state.me ?? account.url;
  upgradeNonUrlId(state, account);
};

const deleteToken = (state: State | Draft<State>, token: string) => {
  delete state.tokens[token];
  state.users = Object.fromEntries(
    Object.entries(state.users).filter(([_, user]) => user.access_token !== token),
  );
  maybeShiftMe(state);
};

const deleteUser = (state: State | Draft<State>, account: Pick<AccountEntity, 'url'>) => {
  const accountUrl = account.url;

  delete state.users[accountUrl];
  state.tokens = Object.fromEntries(
    Object.entries(state.tokens).filter(([_, token]) => token.me !== accountUrl),
  );
  maybeShiftMe(state);
};

const importMastodonPreload = (state: State | Draft<State>, data: Record<string, any>) => {
  const parsedData = v.parse(mastodonPreloadSchema, data);
  const accountId = parsedData.meta.me;
  const accountUrl = parsedData.accounts[accountId]?.url;
  const accessToken = parsedData.meta.access_token;

  if (validId(accessToken) && validId(accountId) && isURL(accountUrl)) {
    state.tokens[accessToken] = v.parse(tokenSchema, {
      access_token: accessToken,
      account: accountId,
      me: accountUrl,
      scope: 'read write follow push',
      token_type: 'Bearer',
    });

    state.users[accountUrl] = v.parse(authUserSchema, {
      id: accountId,
      access_token: accessToken,
      url: accountUrl,
    });
  }

  maybeShiftMe(state);
};

const persistAuthAccount = (account: CredentialAccount) => {
  const persistedAccount = { ...account };
  const key = `authAccount:${account.url}`;

  KVStore.getItem(key)
    .then((oldAccount: any) => {
      const settings = oldAccount?.settings_store ?? {};
      persistedAccount.settings_store ??= settings;
      KVStore.setItem(key, persistedAccount);
    })
    .catch(console.error);

  return persistedAccount;
};

const deleteForbiddenToken = (
  state: State | Draft<State>,
  error: { response: PlfeResponse },
  token: string,
) => {
  if (error.response && [401, 403].includes(error.response.status)) {
    deleteToken(state, token);
    return;
  }

  return state;
};

const updateState = (
  state: State,
  updater: (state: Draft<State>) => void,
  clientUpdater?: (state: State) => InstanceType<typeof PlApiClient>,
) => {
  const oldClient = state.client;

  const newState = create(state, updater);
  const newClient = clientUpdater?.(state) ?? oldClient;
  return { ...newState, client: newClient };
};

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case AUTH_APP_CREATED:
      return updateState(state, (draft) => {
        draft.app = action.app;
      });
    case AUTH_APP_AUTHORIZED:
      return updateState(state, (draft) => {
        if (draft.app) draft.app = { ...draft.app, ...action.token };
      });
    case AUTH_LOGGED_IN:
      return updateState(state, (draft) => {
        importToken(draft, action.token, action.app);
      });
    case AUTH_LOGGED_OUT:
      return updateState(state, (draft) => {
        deleteUser(draft, action.account);
      });
    case VERIFY_CREDENTIALS_SUCCESS:
      return updateState(
        state,
        (draft) => {
          importCredentials(draft, action.token, persistAuthAccount(action.account));
        },
        () => {
          if (!state.me) {
            if (state.client.baseURL === parseBaseURL(action.account.url)) {
              state.client.accessToken = action.token;
              return state.client;
            }

            return new PlApiClient(parseBaseURL(action.account.url) || backendUrl, action.token);
          }
          return state.client;
        },
      );
    case VERIFY_CREDENTIALS_FAIL:
      return updateState(state, (draft) => {
        deleteForbiddenToken(draft, action.error as any, action.token);
      });
    case SWITCH_ACCOUNT:
      return updateState(
        state,
        (draft) => {
          draft.me = action.account.url;
        },
        () => {
          const accessToken = state.users[action.account.url]?.access_token;

          if (state.client.baseURL === parseBaseURL(action.account.url)) {
            state.client.accessToken = accessToken;
            return state.client;
          }

          return new PlApiClient(parseBaseURL(action.account.url) || backendUrl, accessToken);
        },
      );
    case ME_FETCH_SKIP:
      return updateState(state, (draft) => {
        draft.me = null;
      });
    case MASTODON_PRELOAD_IMPORT:
      return updateState(state, (draft) => {
        importMastodonPreload(draft, action.data);
      });
    default:
      return state;
  }
};

const reload = () => {
  location.replace('/');
};

// `me` is a user ID string
const validMe = (state: State) => {
  const me = state.me;
  return typeof me === 'string';
};

// `me` has changed from one valid ID to another
const userSwitched = (oldState: State, state: State) => {
  const me = state.me;
  const oldMe = oldState.me;

  const stillValid = validMe(oldState) && validMe(state);
  const didChange = oldMe !== me;
  const userUpgradedUrl = state.users[me!]?.id === oldMe;

  return stillValid && didChange && !userUpgradedUrl;
};

const maybeReload = (oldState: State, state: State, action: Action) => {
  const loggedOutStandalone = action.type === AUTH_LOGGED_OUT && action.standalone;
  const switched = userSwitched(oldState, state);

  if (switched || loggedOutStandalone) {
    reload();
  }
};

const auth = (oldState: State = initialState, action: Action): State => {
  const state = reducer(oldState, action);

  if (state !== oldState) {
    // Persist the state in localStorage
    persistAuth(state);

    // Reload the page under some conditions
    maybeReload(oldState, state, action);
  }

  return state;
};

export { auth as default };
