import { ACCESS_LEVEL_HUB, ACCESS_LEVEL_PRIVATE } from '@/modules/feeds/Editor/constants';

import { MetadataFeedPlatformModelType, PlatformModel } from '@/modules/feeds/Editor/types';
import type { FeedType } from '@/modules/feeds/types';

import { getDefaultPlatformModelsWhenCreate } from '@/modules/feeds/Editor/components/FormTabs/ModelTab/helpers';
import { AllFieldsType } from '@/modules/feeds/Editor/helpers/requestPayload/getAllFields';

export type ManualFeedPayloadType = {
  id?: number;
  type: string;
  accountId?: number;
  name: string;
  description: string;
  speechToTextProvider: string;
  priorityVerification: boolean;
  feedPriority: number;
  immediateAvailability: boolean;
  skipTaggingForLongClips: boolean;
  maxDurationForTagging: number;
  accessLevel: string;
  accessAllPublishers: boolean;
  iabCategories: string;
  accessVideoOwnerId?: number | null;
  accessPublishers?: { publisherId: number }[];
  keywords: string;
  importPlot: boolean;
  videoFileType: string;
  createClip: boolean;
  automationScript: string;
  platformModels: PlatformModel[];
};

const getManualFields = (
  fields: AllFieldsType,
  metadataPlatformModels: MetadataFeedPlatformModelType[] | null,
): ManualFeedPayloadType => {
  const payload: ManualFeedPayloadType = {
    type: fields.type,
    name: fields.name,
    description: fields.description,
    speechToTextProvider: fields.speechToTextProvider,
    priorityVerification: fields.priorityVerification,
    feedPriority: fields.feedPriority,
    immediateAvailability: fields.immediateAvailability,
    skipTaggingForLongClips: fields.skipTaggingForLongClips,
    maxDurationForTagging: fields.maxDurationForTagging,
    accessLevel: fields.accessLevel,
    accessAllPublishers: fields.accessAllPublishers,
    iabCategories: fields.iabCategories || '[]',
    keywords: fields.keywords,
    importPlot: fields.importPlot,
    videoFileType: fields.videoFileType,
    createClip: fields.createClip,
    automationScript: fields.automationScript || '{}',
    platformModels: fields.platformModels,
  };

  if (fields.id) {
    payload.id = fields.id;
  }

  if (fields.account?.id && !fields.id) {
    payload.accountId = fields.account.id;
  }

  if (fields.accessLevel === ACCESS_LEVEL_PRIVATE && fields.accessVideoOwner?.id) {
    payload.accessVideoOwnerId = fields.accessVideoOwner.id;
  }

  if (fields.accessLevel === ACCESS_LEVEL_HUB && fields.accessPublishers?.length && !fields.accessAllPublishers) {
    payload.accessPublishers = fields.accessPublishers.map((hub) => ({ publisherId: hub.id }));
  }

  if (fields.feedPriority) {
    payload.feedPriority = parseFloat(fields.feedPriority as unknown as string);
  }

  if (fields.platformModels.length === 0 && metadataPlatformModels && !fields.id) {
    payload.platformModels = getDefaultPlatformModelsWhenCreate(metadataPlatformModels, fields.type as FeedType);
  }

  return payload;
};

export default getManualFields;
