import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { OdataGridHelper } from '../_shared/utils/odata-grid-helper';
import { Observable } from 'rxjs';
import { State } from '@progress/kendo-data-query';
import { GridDataResult } from '@progress/kendo-angular-grid';
import { IdName, SaveType, convertDatesToDateOnlyStrings } from '../_shared/utils/util';
import dayjs from 'dayjs';

export interface Item {
  Id: number;
  ProducerName: string;
  ContractDate: Date;
  EffectiveDate: Date;
  BaseFee: number;
  IncFee: number;
  FeeTypeId: number;
  FeeTypeName: string;
}

export interface Detail {
  id: number;
  producerId: number;
  contractDate: Date;
  effectiveDate: Date;
  baseFee: number;
  incFee: number;
  feeTypeId: number;
}

export interface RequiredData {
  hasModifyPermission: boolean;
  producers: IdName[];
  feeTypes: IdName[];
}

@Injectable({
  providedIn: 'root'
})
export class ProducerFeeService extends OdataGridHelper {
  private baseUrl = `${window.location.origin}/api/ProducerFee`;
  http = inject(HttpClient);

  requiredData$ = this.http.get<RequiredData>(`${this.baseUrl}/getRequiredData`)

  getItems(state: State, asOfDate: Date): Observable<GridDataResult> {
    const asOfDateStr = dayjs(asOfDate).format("YYYY-MM-DD");
    return this.fetch(`GetProducerFeeItems`, state, `&asOfDate=${asOfDateStr}`, false);
  }

  getDetail(id: number): Observable<Detail> {
    const url = `${this.baseUrl}/GetDetail?id=${id}`;
    return this.http.get<Detail>(url);
  }

  saveDetail(detail: Detail, SaveType: SaveType): Observable<number> {
    const url = `${this.baseUrl}/SaveDetail?saveType=${SaveType}`;
    detail = convertDatesToDateOnlyStrings(detail, ['contractDate', 'effectiveDate']);
    return this.http.put<number>(url, detail);
  }

  deleteDetail(id: number) {
    const url = `${this.baseUrl}/DeleteDetail/${id}`;
    return this.http.delete(url);
  }

  exportItems(state: State, asOfDate: Date, fileNameOriginal: string) {
    const asOfDateStr = dayjs(asOfDate).format("YYYY-MM-DD");
    return this.fetchExport(`GetProducerFeeItems`, state, `&asOfDate=${asOfDateStr}`, fileNameOriginal);
  }
}
