import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from '../../../core/services/api.service';
import {
  ApprovalResponseDto,
  PaginatedApprovalsResponse,
  RejectionReason,
} from '../../../api/models';

export interface ApproveRequestDto {
  remarks: string;
  reviewedDocuments?: string[];
}

export interface RejectRequestDto {
  remarks: string;
  rejectionReason: RejectionReason;
}

export interface RequestChangesDto {
  remarks: string;
  requiredDocuments: string[];
}

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

  getPendingApprovals(
    page = 1,
    limit = 10
  ): Observable<PaginatedApprovalsResponse> {
    return this.api.get<PaginatedApprovalsResponse>('/approvals/pending', { page, limit });
  }

  getApprovalsByRequest(requestId: string): Observable<ApprovalResponseDto[]> {
    return this.api.get<ApprovalResponseDto[]>(`/requests/${requestId}/approvals`);
  }

  getApproval(approvalId: string): Observable<ApprovalResponseDto> {
    return this.api.get<ApprovalResponseDto>(`/approvals/${approvalId}`);
  }

  approve(requestId: string, dto: ApproveRequestDto): Observable<ApprovalResponseDto> {
    return this.api.post<ApprovalResponseDto>(`/requests/${requestId}/approve`, dto);
  }

  reject(requestId: string, dto: RejectRequestDto): Observable<ApprovalResponseDto> {
    return this.api.post<ApprovalResponseDto>(`/requests/${requestId}/reject`, dto);
  }

  requestChanges(requestId: string, dto: RequestChangesDto): Observable<ApprovalResponseDto> {
    return this.api.post<ApprovalResponseDto>(`/requests/${requestId}/request-changes`, dto);
  }

  getApprovalHistory(requestId: string): Observable<ApprovalResponseDto[]> {
    return this.api.get<ApprovalResponseDto[]>(`/requests/${requestId}/approval-history`);
  }
}
