// src/app/blog/services/blog.service.ts
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import { environment } from '../../../environments/environment.directus';
import { BlogPost, DirectusResponse } from '@core/models/blog-posts.model';

@Injectable({ providedIn: 'root' })
export class BlogService {
  private http = inject(HttpClient);
  private baseUrl = environment.directusUrl;

  private readonly defaultFields = [
    'id',
    'title',
    'slug',
    'summary',
    'cover_image',
    'published_at',
    'tags.tags_id.id',
    'tags.tags_id.name'
  ].join(',');

  getPosts(): Observable<BlogPost[]> {
    const params = new HttpParams()
      .set('sort', '-published_at')
      .set('fields', this.defaultFields)
      .set('filter', JSON.stringify({ status: { _eq: 'published' } }));

    return this.http
      .get<DirectusResponse<BlogPost[]>>(`${this.baseUrl}/items/blog_posts`, { params })
      .pipe(map(res => res.data));
  }

  getPostBySlug(slug: string): Observable<BlogPost | null> {
    const params = new HttpParams()
      .set('filter', JSON.stringify({ slug: { _eq: slug }, status: { _eq: 'published' } }))
      .set('fields', `${this.defaultFields},content`);

    return this.http
      .get<DirectusResponse<BlogPost[]>>(`${this.baseUrl}/items/blog_posts`, { params })
      .pipe(map(res => res.data[0] ?? null));
  }

  getAssetUrl(assetId: string, params?: { width?: number; height?: number; quality?: number }): string {
    const url = new URL(`${this.baseUrl}/assets/${assetId}`);
    if (params?.width) url.searchParams.set('width', String(params.width));
    if (params?.height) url.searchParams.set('height', String(params.height));
    if (params?.quality) url.searchParams.set('quality', String(params.quality));
    return url.toString();
  }
}