import { WidgetDataLoaderInterface } from '@app/event-emitter/dashboards/widget-data-loader-interface';
import {
  AppError,
  createAppError,
  fail,
  Result,
  success,
} from '@app/event-emitter/utils/result';
import { Injectable } from '@nestjs/common';
import { DailyEccmReportsV2Datasource } from 'src/couchdb-datasources/daily-eccm-reports-v2.datasource';

@Injectable()
export class DailyEccmReportsV2DataLoaderService
  implements WidgetDataLoaderInterface<any, any, any>
{
  isMyConfig(): boolean {
    return true;
  }

  async load(
    dataLoaderParams: any,
    dashboardParams: any,
    dashboardId: string,
    widgetId: string,
  ): Promise<Result<any, AppError>> {
    const ds = await DailyEccmReportsV2Datasource.getDatasource();
    const response = await ds.find({
      selector: {
        dashboardId: dashboardId,
        widgetId: widgetId,
        latest: true,
      },
      limit: 1,
    });
    const data = response.docs[0];
    if (!data) {
      return fail(createAppError('No data found'));
    }
    return success(data);
  }
}
