import { HttpClient, HttpParams } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import {
  CalendarConnection,
  CalendarConnectionListResponse,
  CalendarEventsResponse,
  ConnectAppleRequest,
  UpdateCalendarConnectionRequest,
} from '../models/calendar.model';
import { API_URL } from '../tokens/api-url.token';

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

  list(): Observable<CalendarConnectionListResponse> {
    return this.http.get<CalendarConnectionListResponse>(
      `${this.apiUrl}/me/calendar-connections`,
    );
  }

  connectApple(data: ConnectAppleRequest): Observable<CalendarConnection> {
    return this.http.post<CalendarConnection>(
      `${this.apiUrl}/me/calendar-connections/apple`,
      data,
    );
  }

  update(
    id: string,
    data: UpdateCalendarConnectionRequest,
  ): Observable<CalendarConnection> {
    return this.http.patch<CalendarConnection>(
      `${this.apiUrl}/me/calendar-connections/${id}`,
      data,
    );
  }

  disconnect(id: string): Observable<void> {
    return this.http.delete<void>(
      `${this.apiUrl}/me/calendar-connections/${id}`,
    );
  }

  sync(id: string): Observable<CalendarConnection> {
    return this.http.post<CalendarConnection>(
      `${this.apiUrl}/me/calendar-connections/${id}/sync`,
      {},
    );
  }

  listEvents(
    connectionId: string,
    from: string,
    to: string,
    calendarId?: string | null,
  ): Observable<CalendarEventsResponse> {
    let params = new HttpParams().set('from', from).set('to', to);
    if (calendarId) {
      params = params.set('calendarId', calendarId);
    }
    return this.http.get<CalendarEventsResponse>(
      `${this.apiUrl}/me/calendar-connections/${connectionId}/events`,
      { params },
    );
  }
}
