import type { LocationQuery, LocationQueryRaw } from 'vue-router';

const DEV_LOGIN_ACCOUNT = 'admin';
const DEV_LOGIN_QUERY_KEY = 'devLogin';

function normalizeQueryValue(
  value: LocationQuery[string] | LocationQueryRaw[string],
) {
  if (Array.isArray(value)) {
    return value[0] ?? null;
  }
  return value ?? null;
}

export function getDevLoginAccount(query: LocationQuery | LocationQueryRaw) {
  const value = normalizeQueryValue(query[DEV_LOGIN_QUERY_KEY]);
  if (typeof value !== 'string') {
    return null;
  }
  const account = value.trim();
  return account.length > 0 ? account : null;
}

export function removeDevLoginQuery(query: LocationQuery | LocationQueryRaw) {
  const { [DEV_LOGIN_QUERY_KEY]: _ignored, ...nextQuery } = query;
  return nextQuery;
}

export function shouldAttemptDevLogin(params: {
  account: null | string;
  hasAccessToken: boolean;
  isDev: boolean;
}) {
  return (
    params.isDev &&
    !params.hasAccessToken &&
    params.account === DEV_LOGIN_ACCOUNT
  );
}
