import type {
	PersonalSettingsMetricsInterface,
	PodcastDataInterface,
	PodcastMetricsInterface,
	SubscriptionInterface,
} from '../utils/types.ts'
import { getCookie, setCookie } from '../utils/cookies.ts'
import axios from '@nextcloud/axios'
import { defineStore } from 'pinia'
import { generateUrl } from '@nextcloud/router'

export const useSubscriptions = defineStore('subscriptions', {
	state: () => ({
		subs: [] as SubscriptionInterface[],
	}),
	getters: {
		getSubByUrl: (state) => (url: string) =>
			state.subs.find((sub: SubscriptionInterface) => sub.metrics.url === url),
	},
	actions: {
		async fetch() {
			let favorites: string[] = []
			try {
				favorites = JSON.parse(getCookie('repod.favorites') || '[]') || []
			} catch {}

			const metrics = await axios.get<PersonalSettingsMetricsInterface>(
				generateUrl('/apps/gpoddersync/personal_settings/metrics'),
			)

			this.subs = [...metrics.data.subscriptions]
				.sort(
					(a: PodcastMetricsInterface, b: PodcastMetricsInterface) =>
						b.listenedSeconds - a.listenedSeconds,
				)
				.map((sub: PodcastMetricsInterface) => ({
					metrics: sub,
					isFavorite: favorites.includes(sub.url),
					data: this.getSubByUrl(sub.url)?.data,
				}))
		},
		addMetadatas(link: string, data: PodcastDataInterface) {
			this.subs = this.subs.map((sub: SubscriptionInterface) =>
				sub.metrics.url === link ? { ...sub, data } : sub,
			)
		},
		setFavorite(link: string, isFavorite: boolean) {
			this.subs = this.subs.map((sub: SubscriptionInterface) =>
				sub.metrics.url === link ? { ...sub, isFavorite } : sub,
			)

			setCookie(
				'repod.favorites',
				JSON.stringify(
					this.subs
						.filter((sub: SubscriptionInterface) => sub.isFavorite)
						.map((sub: SubscriptionInterface) => sub.metrics.url),
				),
				365,
			)
		},
	},
})
