import { graphql, post, del } from '../api';
import { actorFields, releaseFields } from '../fragments';
import { curateUser } from '../curate';

function initUsersActions(store, _router) {
	async function fetchUser(context, username) {
		const { user } = await graphql(`
			query User(
				$username: String!
				$hasAuth: Boolean!
				$userId: Int
			) {
				user: userByUsername(username: $username) {
					id
					role
					username
					stashes {
						id
						name
						slug
						public
						primary
						actors: stashesActors {
							comment
							actor {
								id
								name
								slug
								gender
								age
								ageFromBirth
								dateOfBirth
								birthCity
								birthState
								birthCountry: countryByBirthCountryAlpha2 {
								  alpha2
								  name
								  alias
								}
								avatar: avatarMedia {
									id
									path
									thumbnail
									lazy
									isS3
									width
									height
									sfw: sfwMedia {
										id
										path
										thumbnail
										lazy
										isS3
										width
										height
									}
								}
							}
						}
						scenes: stashesScenes(
							first: 20
							orderBy: CREATED_AT_DESC
						) {
							comment
							scene {
								${releaseFields}
							}
						}
					}
					alerts {
						id
						notify
						email
						all
						stashes: alertsStashes {
							stash {
								id
								name
								slug
							}
						}
						tags: alertsTags {
							tag {
								id
								name
								slug
							}
						}
						matches: alertsMatches {
							id
							property
							expression
						}
						actors: alertsActors {
							actor {
								${actorFields}
							}
						}
						entities: alertsEntities {
							entity {
								id
								name
								slug
								type
								independent
								hasLogo
								parent {
									id
									name
									slug
									type
									independent
									hasLogo
								}
							}
						}
					}
				}
			}
		`, {
			hasAuth: !!store.state.auth.user,
			userId: store.state.auth.user?.id || null,
			username,
		});

		return curateUser(user);
	}

	async function addAlert(context, alert) {
		return post('/alerts', alert);
	}

	async function removeAlert(context, alertId) {
		return del(`/alerts/${alertId}`);
	}

	return {
		addAlert,
		fetchUser,
		removeAlert,
	};
}

export default initUsersActions;