import { Body, Controller, Get, Param, Post, Put } from '@nestjs/common';
import { DashboardsService } from './dashboards.service';
import { BadRequestErrorHandler, getOrAppErrorOrThrow } from '../utils/result';
import { DashboardsDataService } from './dashboards-data.service';

@Controller('api/dashboard')
export class DashboardController {
  constructor(
    private dashboardsService: DashboardsService,
    private dashboardsDataService: DashboardsDataService,
  ) {}

  @Post()
  async create(): Promise<string> {
    const res = await getOrAppErrorOrThrow(
      () => this.dashboardsService.create(),
      BadRequestErrorHandler,
    );
    return res.id;
  }

  @Get(':id')
  async load(@Param('id') id: string): Promise<any> {
    const res = await getOrAppErrorOrThrow(
      () => this.dashboardsService.load(id),
      BadRequestErrorHandler,
    );
    return res;
  }

  @Get(':id/load-data')
  async loadData(@Param('id') id: string): Promise<any> {
    return await getOrAppErrorOrThrow(
      () => this.dashboardsDataService.loadData(id),
      BadRequestErrorHandler,
    );
  }

  @Get(':id/load-data/:widgetId')
  async loadDataForWidget(
    @Param('id') id: string,
    @Param('widgetId') widgetId: string,
  ): Promise<any> {
    return await getOrAppErrorOrThrow(
      () => this.dashboardsDataService.loadDataForWidget(id, widgetId),
      BadRequestErrorHandler,
    );
  }

  @Put(':id')
  async save(@Param('id') id: string, @Body() data: any): Promise<void> {
    const res = await getOrAppErrorOrThrow(
      () => this.dashboardsService.save(id, data),
      BadRequestErrorHandler,
    );
    return res;
  }
}
