import {
  ERROR_MESSAGE_ALREADY_EXISTS,
  ERROR_MESSAGE_DEFAULT,
  ERROR_MESSAGE_NO_MATCH,
  TAB_GENERAL,
  TAB_PROMOTIONS,
} from '../constants';

import {
  availablePlayers,
  isValidPlaylistUrl,
  matchedPlayersByURL,
} from '@/modules/editorial/RightSideBar/TabPlaylist/Edit/helpers/player';

export const validationScheme = [
  {
    fieldName: 'hub',
    tabId: TAB_GENERAL,
    validation: (value) => {
      if (!value) {
        return 'Hub is required';
      }

      return '';
    },
  },
  {
    fieldName: 'name',
    tabId: TAB_GENERAL,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'url',
    tabId: TAB_GENERAL,
    validation: (value, state) => {
      if (!isValidPlaylistUrl(value)) {
        return ERROR_MESSAGE_DEFAULT;
      }

      const playersByURL = matchedPlayersByURL(value, state.playerOptions);
      if (!playersByURL.length) {
        return ERROR_MESSAGE_NO_MATCH;
      }

      if (!availablePlayers(playersByURL, state.playlistsByUrl).length) {
        return ERROR_MESSAGE_ALREADY_EXISTS;
      }

      return '';
    },
  },
  {
    fieldName: 'player',
    tabId: TAB_GENERAL,
    validation: (value) => {
      if (!value) {
        return 'Player is required';
      }

      return '';
    },
  },
  {
    fieldName: 'frequency',
    tabId: TAB_PROMOTIONS,
    validation: (value, state) => {
      if (!state.includeSponsoredContent) {
        return '';
      }

      if (!value) {
        return 'empty';
      }

      if (value < 1 || value > 10) {
        return 'between 1 and 10';
      }

      return '';
    },
  },
  {
    fieldName: 'supplyTag',
    tabId: TAB_PROMOTIONS,
    validation: (value, state) => {
      if (!state.includeSponsoredContent) {
        return '';
      }

      if (!value || !value.id) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
];
