'use strict';

const { makeExtendSchemaPlugin, gql } = require('graphile-utils');

const schemaExtender = makeExtendSchemaPlugin(_build => ({
	typeDefs: gql`
	  extend type Release {
		isFavorited: Boolean @requires(columns: ["stashesScenesBySceneId"])
		isStashed(includeFavorites: Boolean = false): Boolean @requires(columns: ["stashesScenesBySceneId"])
	  }
    `,
	resolvers: {
		Release: {
			isFavorited(parent) {
				if (!parent['@stashes'] || (parent['@stashes'].length > 0 && typeof parent['@stashes'][0]['@stash'].primary === 'undefined')) {
					return null;
				}

				return parent['@stashes'].some(({ '@stash': stash }) => stash.primary);
			},
			isStashed(parent, args) {
				if (!parent['@stashes'] || (parent['@stashes'].length > 0 && typeof parent['@stashes'][0]['@stash'].primary === 'undefined')) {
					return null;
				}

				if (args.includeFavorites) {
					return parent['@stashes'].length > 0;
				}

				return parent['@stashes'].some(({ '@stash': stash }) => !stash.primary);
			},
		},
	},
}));

module.exports = [schemaExtender];