import { HttpClient, HttpParams } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Booking, BookingListResponse } from '../models/booking.model';
import { API_URL } from '../tokens/api-url.token';

export interface BookingListParams {
  status?: string;
  from?: string;
  to?: string;
  page?: number;
  limit?: number;
}

@Injectable({ providedIn: 'root' })
export class BookingApiService {
  constructor(
    private http: HttpClient,
    @Inject(API_URL) private apiUrl: string,
  ) {}

  list(params: BookingListParams = {}): Observable<BookingListResponse> {
    let httpParams = new HttpParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        httpParams = httpParams.set(key, String(value));
      }
    });
    return this.http.get<BookingListResponse>(`${this.apiUrl}/me/bookings`, {
      params: httpParams,
    });
  }

  cancel(id: string, reason?: string): Observable<Booking> {
    return this.http.post<Booking>(`${this.apiUrl}/me/bookings/${id}/cancel`, {
      reason,
    });
  }

  reschedule(id: string, startTime: string): Observable<Booking> {
    return this.http.post<Booking>(
      `${this.apiUrl}/me/bookings/${id}/reschedule`,
      { startTime },
    );
  }

  updateOutcome(
    id: string,
    data: { meetingOutcome: 'held' | 'no_show' | 'unknown'; hostRating?: number | null },
  ): Observable<Booking> {
    return this.http.patch<Booking>(`${this.apiUrl}/me/bookings/${id}/outcome`, data);
  }
}
