// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, map, tap, catchError, of } from 'rxjs';
import { ConfigService } from './config.service';

export interface ServiceFavorite {
	srv_id: number;
	cmp_id: number;
}

@Injectable({
	providedIn: 'root',
})
export class FavoritesService {
	private favoriteIds = new BehaviorSubject<Set<string>>(new Set());
	favoriteIds$ = this.favoriteIds.asObservable();

	constructor(private http: HttpClient, private configService: ConfigService) {}

	private get baseUrl(): string {
		return this.configService.serviceUrl_Companies + 'favorites/services';
	}

	private toKey(srv_id: number, cmp_id: number): string {
		return `${srv_id}_${cmp_id}`;
	}

	/** Carica i preferiti dal backend */
	loadFavorites(): Observable<Set<string>> {
		return this.http.get<ServiceFavorite[]>(this.baseUrl, { observe: 'response' }).pipe(
			map((res) => {
				const ids = new Set<string>();
				(res.body || []).forEach((f) => ids.add(this.toKey(f.srv_id, f.cmp_id)));
				return ids;
			}),
			tap((ids) => this.favoriteIds.next(ids)),
			catchError(() => {
				return of(this.favoriteIds.value);
			}),
		);
	}

	/** Verifica se un servizio e' tra i preferiti */
	isFavorite(srv_id: number, cmp_id: number): boolean {
		return this.favoriteIds.value.has(this.toKey(srv_id, cmp_id));
	}

	/** Verifica per chiave stringa (srv_id_cmp_id) */
	isFavoriteByKey(key: string): boolean {
		return this.favoriteIds.value.has(key);
	}

	/** Ottieni il Set corrente */
	getFavoriteIds(): Set<string> {
		return this.favoriteIds.value;
	}

	/** Toggle preferito (aggiunge o rimuove) */
	toggleFavorite(srv_id: number, cmp_id: number): void {
		const key = this.toKey(srv_id, cmp_id);
		const current = new Set(this.favoriteIds.value);

		if (current.has(key)) {
			current.delete(key);
			this.favoriteIds.next(current);
			this.http
				.delete(this.baseUrl, { body: { srv_id, cmp_id }, observe: 'response' })
				.pipe(catchError(() => of(null)))
				.subscribe();
		} else {
			current.add(key);
			this.favoriteIds.next(current);
			this.http
				.post(this.baseUrl, { srv_id, cmp_id }, { observe: 'response' })
				.pipe(catchError(() => of(null)))
				.subscribe();
		}
	}
}
