import moment from 'moment';

/**
 * Parse ticket details to determine if the ticket is on sale, sale has not started, or sale has ended.
 *
 * @since 6.2.0
 * @param {Object} ticketDetails The ticket details.
 * @return {Object} The parsed details.
 */
function parseTicketDetails(ticketDetails) {
	const {
		startDateMoment,
		endDateMoment,
		capacity,
	} = ticketDetails;

	const capacityType = ticketDetails?.capacityType || 'limited';

	const now = moment();

	let isOnSale = false,
		saleHasNotStarted = false,
		saleHasEnded = false;

	// If the start date is in the past, set it to now.
	if ( startDateMoment.isBefore( now ) && endDateMoment.isAfter( now ) ) {
		isOnSale = true;
	}

	if ( startDateMoment.isAfter( now ) ) {
		saleHasNotStarted = true;
	}

	if ( endDateMoment.isBefore( now ) ) {
		saleHasEnded = true;
	}

	return {
		capacity: 'unlimited' === capacityType ? -1 : capacity,
		isOnSale,
		saleHasNotStarted,
		saleHasEnded
	};
}

/**
 * The store actions.
 *
 * @since 6.2.0
 */
export const actions = {
	setUsingAssignedSeating(usingAssignedSeating) {
		return {
			type: 'SET_USING_ASSIGNED_SEATING',
			usingAssignedSeating,
		};
	},
	reflectTicketChange(ticketId, ticketDetails, isCreate = false ) {
		return {
			type: 'TICKET_CHANGED',
			ticketId,
			isCreate,
			...parseTicketDetails(ticketDetails),
		};
	},
	reflectTicketDeletion(ticketId) {
		return {
			type: 'TICKET_DELETED',
			ticketId,
		};
	},
	setWaitlistStatus(enabled, blockType) {
		return {
			type: 'WAITLIST_STATUS_CHANGED',
			enabled,
			blockType
		};
	},
	setWaitlistConditional(conditional, blockType) {
		return {
			type: 'WAITLIST_CONDITIONAL_CHANGED',
			conditional,
			blockType
		};
	},
	reflectRSVPChange(payload, isCreate) {
		return {
			type: 'RSVP_CHANGED',
			ticketId: payload.id,
			isCreate,
			...parseTicketDetails( payload )
		};
	},
	reflectRSVPDeletion(rsvpId) {
		return {
			type: 'RSVP_DELETED',
			rsvpId
		};
	}
};
