import { Body, Controller, Get, Headers, HttpCode, Post, Query } from '@nestjs/common';
import { GrafanaProxyService } from './grafana-proxy.service';

type GrafanaQueryPayload = Record<string, unknown>;

@Controller('grafana-proxy')
export class GrafanaProxyController {
  constructor(private readonly grafanaProxyService: GrafanaProxyService) {}

  @Get('zabbix/hosts')
  @HttpCode(200)
  async listZabbixHosts(
    @Headers('x-api-key') apiKey?: string,
    @Headers('x-grafana-org-id') orgIdHeader?: string
  ): Promise<{ hosts: string[]; rows: Array<{ text: string; value: string }> }> {
    return this.grafanaProxyService.listZabbixHosts(apiKey, orgIdHeader);
  }

  @Get('zabbix/summary')
  @HttpCode(200)
  async getZabbixSummary(
    @Headers('x-api-key') apiKey?: string,
    @Headers('x-grafana-org-id') orgIdHeader?: string
  ): Promise<{ rows: Array<Record<string, string | number | null>> }> {
    return this.grafanaProxyService.getZabbixSummary(apiKey, orgIdHeader);
  }

  @Get('zabbix/host-detail')
  @HttpCode(200)
  async getZabbixHostDetail(
    @Headers('x-api-key') apiKey?: string,
    @Headers('x-grafana-org-id') orgIdHeader?: string,
    @Query('host') hostName?: string,
    @Query('view') view?: string,
    @Query('contains') contains?: string
  ): Promise<{ host: string; rows: Array<Record<string, string | number | null>> }> {
    return this.grafanaProxyService.getZabbixHostDetail(
      apiKey,
      orgIdHeader,
      hostName,
      view,
      contains
    );
  }

  @Get('zabbix/host-metrics')
  @HttpCode(200)
  async getZabbixHostMetrics(
    @Headers('x-api-key') apiKey?: string,
    @Headers('x-grafana-org-id') orgIdHeader?: string,
    @Query('host') hostName?: string,
    @Query('metric') metric?: string,
    @Query('from') from?: string,
    @Query('to') to?: string
  ): Promise<{ host: string; rows: Array<Record<string, string | number>> }> {
    return this.grafanaProxyService.getZabbixHostMetrics(
      apiKey,
      orgIdHeader,
      hostName,
      metric,
      from,
      to
    );
  }

  @Get('zabbix/host-status')
  @HttpCode(200)
  async getZabbixHostStatus(
    @Headers('x-api-key') apiKey?: string,
    @Headers('x-grafana-org-id') orgIdHeader?: string,
    @Query('host') hostName?: string
  ): Promise<{
    host: string;
    status_summary: string | null;
    uptime_human: string | null;
    rows: Array<{ label: string; value: string | null }>;
  }> {
    return this.grafanaProxyService.getZabbixHostStatus(apiKey, orgIdHeader, hostName);
  }

  @Post('query')
  @HttpCode(200)
  async query(
    @Body() body: GrafanaQueryPayload,
    @Headers('x-api-key') apiKey?: string,
    @Headers('x-grafana-org-id') orgIdHeader?: string
  ): Promise<unknown> {
    return this.grafanaProxyService.query(body, apiKey, orgIdHeader);
  }
}
