import {
  Controller,
  Get,
  Param,
  Query,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiParam,
  ApiQuery,
} from '@nestjs/swagger';
import { StatusService } from './status.service';
import { RequirePermissions } from '../../../auth/permissions/permissions.decorator';
import { Permission } from '../../../auth/permissions/permissions.enum';

@ApiTags('integrations/status')
@ApiBearerAuth('JWT-auth')
@Controller('integrations/status')
export class StatusController {
  constructor(private readonly statusService: StatusService) {}

  @Get('health')
  @RequirePermissions(Permission.INTEGRATIONS_VIEW)
  @ApiOperation({ summary: 'Get aggregated health status for all integrations' })
  @ApiQuery({
    name: 'refresh',
    required: false,
    type: Boolean,
    description: 'Force refresh cache',
  })
  @ApiResponse({
    status: 200,
    description: 'Aggregated health status',
    schema: {
      type: 'object',
      properties: {
        overall: { type: 'string', enum: ['healthy', 'degraded', 'unhealthy'] },
        totalIntegrations: { type: 'number' },
        healthyCount: { type: 'number' },
        degradedCount: { type: 'number' },
        unhealthyCount: { type: 'number' },
        unknownCount: { type: 'number' },
        integrations: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              id: { type: 'string' },
              type: { type: 'string' },
              name: { type: 'string' },
              status: { type: 'string' },
              syncStatus: { type: 'string' },
              lastSync: { type: 'string', format: 'date-time', nullable: true },
              latency: { type: 'number', nullable: true },
              message: { type: 'string' },
            },
          },
        },
        lastChecked: { type: 'string', format: 'date-time' },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getAggregatedHealth(@Query('refresh') refresh?: boolean) {
    return this.statusService.getAggregatedHealth(refresh === true);
  }

  @Get('health/:id')
  @RequirePermissions(Permission.INTEGRATIONS_VIEW)
  @ApiOperation({ summary: 'Get health status for a single integration' })
  @ApiParam({ name: 'id', description: 'Credential ID' })
  @ApiResponse({
    status: 200,
    description: 'Integration health status',
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  @ApiResponse({ status: 404, description: 'Credential not found' })
  getIntegrationHealth(@Param('id') id: string) {
    return this.statusService.getIntegrationHealth(id);
  }

  @Get('summary')
  @RequirePermissions(Permission.INTEGRATIONS_VIEW)
  @ApiOperation({ summary: 'Get summary of integrations by type' })
  @ApiResponse({
    status: 200,
    description: 'Integration type summary',
    schema: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          type: { type: 'string' },
          count: { type: 'number' },
          activeCount: { type: 'number' },
          healthyCount: { type: 'number' },
          lastSync: { type: 'string', format: 'date-time', nullable: true },
          hasErrors: { type: 'boolean' },
        },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getTypeSummary() {
    return this.statusService.getTypeSummary();
  }

  @Get('errors')
  @RequirePermissions(Permission.INTEGRATIONS_VIEW)
  @ApiOperation({ summary: 'Get recent integration errors' })
  @ApiQuery({
    name: 'limit',
    required: false,
    type: Number,
    description: 'Maximum number of errors to return (default: 10)',
  })
  @ApiResponse({
    status: 200,
    description: 'List of recent errors',
    schema: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          credentialId: { type: 'string' },
          type: { type: 'string' },
          name: { type: 'string' },
          error: { type: 'string' },
          occurredAt: { type: 'string', format: 'date-time' },
        },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getRecentErrors(@Query('limit') limit?: number) {
    return this.statusService.getRecentErrors(limit || 10);
  }

  @Get('statistics')
  @RequirePermissions(Permission.INTEGRATIONS_VIEW)
  @ApiOperation({ summary: 'Get sync statistics for a time period' })
  @ApiQuery({
    name: 'from',
    required: false,
    type: String,
    description: 'Start date (ISO format, default: 24 hours ago)',
  })
  @ApiQuery({
    name: 'to',
    required: false,
    type: String,
    description: 'End date (ISO format, default: now)',
  })
  @ApiResponse({
    status: 200,
    description: 'Sync statistics',
    schema: {
      type: 'object',
      properties: {
        totalSyncs: { type: 'number' },
        successfulSyncs: { type: 'number' },
        failedSyncs: { type: 'number' },
        successRate: { type: 'number' },
        averageDuration: { type: 'number' },
        totalRecordsProcessed: { type: 'number' },
        byType: {
          type: 'object',
          additionalProperties: {
            type: 'object',
            properties: {
              success: { type: 'number' },
              failed: { type: 'number' },
            },
          },
        },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getSyncStatistics(
    @Query('from') from?: string,
    @Query('to') to?: string,
  ) {
    const fromDate = from ? new Date(from) : undefined;
    const toDate = to ? new Date(to) : undefined;
    return this.statusService.getSyncStatistics(fromDate, toDate);
  }
}
