import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import {
  BookingConfirmation,
  CancelBookingResponse,
  CreateBookingRequest,
} from '../models/booking.model';
import { PublicEventPage, PublicHostPage } from '../models/event-type.model';
import { SlotsResponse } from '../models/slot.model';
import { API_URL } from '../tokens/api-url.token';

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

  getHostPage(username: string): Observable<PublicHostPage> {
    return this.http.get<PublicHostPage>(
      `${this.apiUrl}/public/${encodeURIComponent(username)}`,
    );
  }

  getEventPage(username: string, eventSlug: string): Observable<PublicEventPage> {
    return this.http.get<PublicEventPage>(
      `${this.apiUrl}/public/${encodeURIComponent(username)}/${encodeURIComponent(eventSlug)}`,
    );
  }

  getSlots(
    username: string,
    eventSlug: string,
    from: string,
    to: string,
    timezone: string,
  ): Observable<SlotsResponse> {
    const params = new HttpParams()
      .set('from', from)
      .set('to', to)
      .set('timezone', timezone);
    return this.http.get<SlotsResponse>(
      `${this.apiUrl}/public/${encodeURIComponent(username)}/${encodeURIComponent(eventSlug)}/slots`,
      { params },
    );
  }

  createBooking(
    username: string,
    eventSlug: string,
    data: CreateBookingRequest,
    embedKey?: string,
  ): Observable<BookingConfirmation> {
    const headers = new HttpHeaders({
      'Idempotency-Key': crypto.randomUUID(),
      ...(embedKey ? { 'X-Embed-Key': embedKey } : {}),
    });
    return this.http.post<BookingConfirmation>(
      `${this.apiUrl}/public/${encodeURIComponent(username)}/${encodeURIComponent(eventSlug)}/bookings`,
      data,
      { headers },
    );
  }

  cancelBooking(token: string): Observable<CancelBookingResponse> {
    return this.http.post<CancelBookingResponse>(
      `${this.apiUrl}/public/cancel`,
      { token },
    );
  }

  submitFeedback(data: {
    token: string;
    guestRating: number;
    guestFeedback?: string | null;
  }): Observable<{ message: string; guestRating: number }> {
    return this.http.post<{ message: string; guestRating: number }>(
      `${this.apiUrl}/public/feedback`,
      data,
    );
  }
}
