import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, forkJoin, of } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
import { ApiResponse, PaginatedResponse } from '../models/api.model';
import {
  SalesCommission,
  SalesCommissionRule,
  CreateSalesCommissionRule,
  UpdateSalesCommissionRule,
} from '../models/sales-commission.model';

@Injectable({ providedIn: 'root' })
export class SalesCommissionService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.apiUrl}/sales/commissions`;

  private buildParams(filters?: Record<string, any>): HttpParams {
    let params = new HttpParams();
    if (filters) {
      Object.entries(filters).forEach(([key, value]) => {
        if (value != null && value !== '') {
          params = params.set(key, String(value));
        }
      });
    }
    return params;
  }

  list(page = 1, perPage = 100, filters?: Record<string, any>): Observable<PaginatedResponse<SalesCommission>> {
    let params = this.buildParams(filters)
      .set('page', page)
      .set('per_page', perPage);
    return this.http.get<PaginatedResponse<SalesCommission>>(this.apiUrl, { params });
  }

  summary(filters?: Record<string, any>): Observable<{ data: any }> {
    const params = this.buildParams(filters);
    return this.http.get<{ data: any }>(`${this.apiUrl}/summary`, { params });
  }

  approve(id: number): Observable<ApiResponse<SalesCommission>> {
    return this.http.post<ApiResponse<SalesCommission>>(`${this.apiUrl}/${id}/approve`, {});
  }

  markPaid(id: number, data?: any): Observable<ApiResponse<SalesCommission>> {
    return this.http.post<ApiResponse<SalesCommission>>(`${this.apiUrl}/${id}/mark-paid`, data || {});
  }

  bulkApprove(ids: number[]): Observable<{ message: string }> {
    return this.http.post<{ message: string }>(`${this.apiUrl}/bulk-approve`, { ids });
  }

  bulkMarkPaid(data: any): Observable<{ message: string }> {
    return this.http.post<{ message: string }>(`${this.apiUrl}/bulk-mark-paid`, data);
  }

  // ─── Commission Rules ──────────────────────────────────────────

  getRules(): Observable<{ data: SalesCommissionRule[] }> {
    return this.http.get<{ data: SalesCommissionRule[] }>(`${this.apiUrl}/rules`);
  }

  createRule(data: CreateSalesCommissionRule): Observable<ApiResponse<SalesCommissionRule>> {
    return this.http.post<ApiResponse<SalesCommissionRule>>(`${this.apiUrl}/rules`, data);
  }

  updateRule(id: number, data: UpdateSalesCommissionRule): Observable<ApiResponse<SalesCommissionRule>> {
    return this.http.put<ApiResponse<SalesCommissionRule>>(`${this.apiUrl}/rules/${id}`, data);
  }

  deleteRule(id: number): Observable<{ message: string }> {
    return this.http.delete<{ message: string }>(`${this.apiUrl}/rules/${id}`);
  }
}
