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

import { ApiService } from './api.service';
import {
    Product,
    ProductList,
    ProductListConfig,
    ProductListFilters,
    ProductPageData,
    ProductsPageData,
} from '@models';

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

    private _apiDomain = '/ecommerce';

    query(config: ProductListConfig): Observable<ProductList> {
        // Convert any filters over to Angular's URLSearchParams
        const params: ProductListFilters = {} as ProductListFilters;
        Object.assign(params, config.filters);
        return this.apiService.get(
            `${this._apiDomain}/products` + (config.type === 'feed' ? '/feed' : ''),
            new HttpParams({ fromObject: <
                    {
                        [param: string]: string | number | boolean | readonly (string | number | boolean)[];
                    }
                >params }),
        );
    }

    get(slug: string): Observable<ProductsPageData> {
        return this.apiService.get(`${this._apiDomain}/product/${slug}`);
    }

    getProductBySlug(slug: string): Observable<ProductPageData> {
        return this.apiService.get(`${this._apiDomain}/product/${slug}`);
    }

    getAll(): Observable<Array<Product>> {
        return this.apiService.get(`${this._apiDomain}/products`).pipe(map((data) => data.products));
    }

    getAllByCategory(category: string): Observable<ProductsPageData> {
        return this.apiService.get(`${this._apiDomain}/products/${category}`); //.pipe(map(data => data.products));
    }

    create(product: Product): Observable<Product> {
        return this.apiService
            .post(`${this._apiDomain}/products/`, { product: product })
            .pipe(map((data) => data.product));
    }

    update(product: Product): Observable<Product> {
        return this.apiService
            .put(`${this._apiDomain}/products/${product.slug}`, { product: product })
            .pipe(map((data) => data.product));
    }

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

    save(product: Product): Observable<Product> {
        // If we're updating an existing product
        if (product.slug) {
            return this.apiService
                .put(`${this._apiDomain}/products/${product.slug}`, { product: product })
                .pipe(map((data) => data.product));

            // Otherwise, create a new product
        } else {
            return this.apiService
                .post(`${this._apiDomain}/products/`, { product: product })
                .pipe(map((data) => data.product));
        }
    }
}
