import { IPortfolioEntry, CONTRACT_INTERFACES } from '../../'
import CI = CONTRACT_INTERFACES

const add = (
	isOpen: boolean,
	pricing: CI.ITradeIdeaPricing,
	ticker: string,
	allocation: number,
	notes: string,
	title?: string,
	direction?: 'long' | 'short',
	assetDescription?: string,
	reference?: string,
	assetImage?: CI.ITradeIdeaImage,
	alternativeProviderSymbols?: CI.ITradeIdeaIdeaAlternativeProviderSymbol[],
): IPortfolioEntry => {
	if (isOpen) {
		if (title === undefined || typeof title !== 'string') {
			throw new Error('title is required when you open a new idea')
		} else {
			if (title!.length === 0) {
				throw new Error('title is required when you open a new idea')
			}
		}
		if (
			assetDescription === undefined ||
			typeof assetDescription !== 'string'
		) {
			throw new Error(
				'assetDescription is required when you open a new idea',
			)
		} else {
			if (assetDescription!.length === 0) {
				throw new Error(
					'assetDescription is required when you open a new idea',
				)
			}
		}
		if (
			direction === undefined ||
			(direction !== 'long' && direction !== 'short')
		) {
			throw new Error(
				'direction is required when you open a new idea and it must be "open" or "short"',
			)
		}
	}
	const entry: IPortfolioEntry = {
		reference,
		pricing: { ...pricing },
		notes,
		title,
		asset: {
			ticker,
			description: assetDescription,
			image: assetImage,
			alternativeProviderSymbols,
		},
		direction: isOpen ? direction : undefined, // only for open
		// reuse in open and for calculate adjustment
		allocation,
	}
	return entry
}

export const portfolio = {
	add,
	open: (
		title: string,
		notes: string,
		pricing: CI.ITradeIdeaPricing,
		ticker: string,
		assetDescription: string,
		direction: 'long' | 'short',
		allocation: number,
		reference?: string,
		assetImage?: CI.ITradeIdeaImage,
		alternativeProviderSymbols?: CI.ITradeIdeaIdeaAlternativeProviderSymbol[],
	): IPortfolioEntry => {
		return add(
			true,
			pricing,
			ticker,
			allocation,
			notes,
			title,
			direction,
			assetDescription,
			reference,
			assetImage,
			alternativeProviderSymbols,
		)
	},
	adjust: (
		notes: string,
		pricing: CI.ITradeIdeaPricing,
		ticker: string,
		allocation: number,
		reference?: string,
	): IPortfolioEntry => {
		return add(
			false,
			pricing,
			ticker,
			allocation,
			notes,
			undefined,
			undefined,
			undefined,
			reference,
		)
	},
	close: (
		notes: string,
		pricing: CI.ITradeIdeaPricing,
		ticker: string,
		reference?: string,
	): IPortfolioEntry => {
		return add(
			false,
			pricing,
			ticker,
			0,
			notes,
			undefined,
			undefined,
			undefined,
			reference,
		)
	},
}
