import { Injectable, inject } from '@angular/core';
import { HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

import { ApiService } from './api.service';
import { Application, ApplicationList, ApplicationListConfig, ApplicationListFilters } from '@models';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class ApplicationsService {
    private apiService = inject(ApiService);

    private _apiDomain = '/skydive';

    query(config: ApplicationListConfig): Observable<ApplicationList> {
        // Convert any filters over to Angular's URLSearchParams
        const params: ApplicationListFilters = {
            apikey: config.filters.apikey,
            author: config.filters.author,
            limit: config.filters.limit,
            offset: config.filters.offset,
        };
        return this.apiService.get(
            `${this._apiDomain}/applications` + (config.type === 'feed' ? '/feed' : ''),
            new HttpParams({ fromObject: <
                    {
                        [param: string]: string | number | boolean | readonly (string | number | boolean)[];
                    }
                >params }),
        );
    }

    get(slug: string): Observable<Application> {
        return this.apiService.get(`${this._apiDomain}/applications/${slug}`).pipe(map((data) => data.application));
    }

    destroy(slug: string): Observable<boolean> {
        return this.apiService.delete(`${this._apiDomain}/applications/${slug}`).pipe(map((data) => data.deleted));
    }

    save(application: Application): Observable<Application> {
        if (application.slug) {
            // If we're updating an existing application
            return this.apiService
                .put(`${this._apiDomain}/applications/${application.slug}`, { application: application })
                .pipe(map((data) => data.application));
        } else {
            // Otherwise, create a new application
            return this.apiService
                .post(`${this._apiDomain}/applications/`, { application: application })
                .pipe(map((data) => data.application));
        }
    }
}
