import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from '../../../core/services/api.service';
import {
  WebhookResponseDto,
  CreateWebhookDto,
  UpdateWebhookDto,
  WebhookTestResultDto,
  WebhookLogEntryDto,
  PaginatedWebhookLogsResponse,
} from '../../../api/models';

@Injectable({
  providedIn: 'root',
})
export class WebhookService {
  private readonly api = inject(ApiService);

  getWebhooks(): Observable<WebhookResponseDto[]> {
    return this.api.get<WebhookResponseDto[]>('/webhooks');
  }

  getWebhook(id: string): Observable<WebhookResponseDto> {
    return this.api.get<WebhookResponseDto>(`/webhooks/${id}`);
  }

  createWebhook(dto: CreateWebhookDto): Observable<WebhookResponseDto> {
    return this.api.post<WebhookResponseDto>('/webhooks', dto);
  }

  updateWebhook(id: string, dto: UpdateWebhookDto): Observable<WebhookResponseDto> {
    return this.api.patch<WebhookResponseDto>(`/webhooks/${id}`, dto);
  }

  deleteWebhook(id: string): Observable<void> {
    return this.api.delete<void>(`/webhooks/${id}`);
  }

  testWebhook(id: string): Observable<WebhookTestResultDto> {
    return this.api.post<WebhookTestResultDto>(`/webhooks/${id}/test`, {});
  }

  getWebhookLogs(id: string, page = 1, limit = 20): Observable<PaginatedWebhookLogsResponse> {
    return this.api.get<PaginatedWebhookLogsResponse>(`/webhooks/${id}/logs`, { page, limit });
  }

  toggleActive(id: string, isActive: boolean): Observable<WebhookResponseDto> {
    return this.api.patch<WebhookResponseDto>(`/webhooks/${id}`, { isActive });
  }
}
