import {StaticResponse, RouteHandler} from 'cypress/types/net-stubbing';

function parseUrl(url: string) {
  return `http://*${
    url.indexOf('/') === 0 ? '' : '/'
  }${url}${
    url.includes('*') ? '' : '*'
  }`;
}

export function normalIntercept(
  url: string,
  fixture: string,
  options?: Omit<RouteHandler, 'fixture'>,
) {
  return cy.intercept(
    parseUrl(url),
    {fixture, ...(options ?? {})},
  );
}

export function successIntercept(url: string) {
  return normalIntercept(
    url,
    'success',
    {delay: 100},
  );
}

export function intercept(
  url: string,
  response: (e: {
    url: string,
    reply: (params: StaticResponse) => void,
  }) => void,
) {
  cy.intercept(
    parseUrl(url),
    function(res) {
      function reply(params: StaticResponse) {
        return res.reply({delay: 100, ...params});
      }

      response({url: res.url, reply});
    },
  );
}

export function loginSetup() {
  cy.visit('/');

  cy.get('input[name="accountName"]').type('admin');
  cy.get('input[name="accountPassword"]').type('tld123');

  cy.getTestId('login_form').submit();
}

export function loginIntercept() {
  normalIntercept('/user/login', 'login').as('loginIntercept');
}

export function menuIntercept() {
  normalIntercept('/menu/getUserMenu', 'menu/basic')
    .as('menuIntercept');
}

export function optionsIntercept() {
  normalIntercept('/role/roleBefore', 'role/options');
  normalIntercept('/department/getDepartBefor', 'department/options');
  normalIntercept('/storage/getStorageAll', 'storage/options');
}

export function exportIntercept(url: string) {
  successIntercept(url).as('export');
}
