import { completeAccountLogin, createAccount, removeAccount, removeAllAccounts, startAccountLogin, updateAccountLabel } from "./accounts.js";
import { readJson } from "./http.js";

export async function resolveAccountRoute(req, url, context) {
  if (req.method === "POST" && url.pathname === "/account-login-attempts") {
    return {
      status: 201,
      body: await context.accountLoginAttempts.start(await readJson(req))
    };
  }

  const attemptCompleteMatch = url.pathname.match(/^\/account-login-attempts\/([^/]+)\/complete$/);
  if (req.method === "POST" && attemptCompleteMatch) {
    return {
      status: 200,
      body: await context.accountLoginAttempts.complete(decodeURIComponent(attemptCompleteMatch[1]))
    };
  }

  const attemptMatch = url.pathname.match(/^\/account-login-attempts\/([^/]+)$/);
  if (req.method === "DELETE" && attemptMatch) {
    return {
      status: 200,
      body: await context.accountLoginAttempts.cancel(decodeURIComponent(attemptMatch[1]))
    };
  }

  if (req.method === "POST" && url.pathname === "/accounts") {
    const create = context.createAccount ?? createAccount;
    return {
      status: 201,
      body: await create(context.config, context.configPath, await readJson(req), {
        assertCanAddExecutionAccount: context.assertCanAddExecutionAccount
      })
    };
  }

  if (req.method === "DELETE" && url.pathname === "/accounts") {
    const removeAll = context.removeAllAccounts ?? removeAllAccounts;
    return {
      status: 200,
      body: await removeAll(context.config, context.configPath)
    };
  }

  const loginCompleteMatch = url.pathname.match(/^\/accounts\/([^/]+)\/login\/complete$/);
  if (req.method === "POST" && loginCompleteMatch) {
    const complete = context.completeAccountLogin ?? completeAccountLogin;
    return {
      status: 200,
      body: await complete(context.config, context.configPath, decodeURIComponent(loginCompleteMatch[1]))
    };
  }

  const loginMatch = url.pathname.match(/^\/accounts\/([^/]+)\/login$/);
  if (req.method === "POST" && loginMatch) {
    const startLogin = context.startAccountLogin ?? startAccountLogin;
    return {
      status: 200,
      body: await startLogin(context.config, decodeURIComponent(loginMatch[1]))
    };
  }

  const match = url.pathname.match(/^\/accounts\/([^/]+)$/);
  if ((req.method === "PATCH" || req.method === "PUT") && match) {
    const update = context.updateAccountLabel ?? updateAccountLabel;
    return {
      status: 200,
      body: await update(context.config, context.configPath, decodeURIComponent(match[1]), await readJson(req))
    };
  }

  if (req.method === "DELETE" && match) {
    const remove = context.removeAccount ?? removeAccount;
    return {
      status: 200,
      body: await remove(context.config, context.configPath, decodeURIComponent(match[1]), {
        tokenUsageStore: context.tokenUsageStore,
        logger: context.logger
      })
    };
  }

  return null;
}
