import {
  Controller,
  Get,
  Param,
  ParseIntPipe,
  Res,
  Logger,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import { Response } from 'express';
import { ApiOperation, ApiBearerAuth, ApiSecurity, ApiResponse } from '@nestjs/swagger';
import { ResponseService } from 'src/common/response-handling/response-handler';
import { handleControllerError } from 'src/common/utils/controller-response-handling';
import { CombinedAuthGuard } from 'src/auth/combined-auth.guard';
import { RolesGuard } from 'src/common/guards/roles.guard';
import { Roles } from 'src/common/decorators/roles.decorator';
import { CommunicationConfigReadService } from './service/communication-config-read.service';

/**
 * Read endpoints backing the Add Program communication-config accordion.
 * This codebase has no global version prefix; newer controllers opt into a `v1/`
 * segment in their own path (e.g. v1/program-templates), so these new routes follow suit.
 */
@Controller()
@UseGuards(CombinedAuthGuard, RolesGuard)
@Roles('admin', 'mahatria', 'viewer', 'shoba')
@ApiBearerAuth('Authorization')
@ApiSecurity('userIdAuth')
@ApiSecurity('activeRoleAuth')
export class CommunicationConfigController {
  private readonly logger = new Logger(CommunicationConfigController.name);

  constructor(
    private readonly readService: CommunicationConfigReadService,
    private readonly responseService: ResponseService,
  ) {}

  /**
   * Preview for new programs: steps + master templates with isEnabled = master.is_default.
   */
  @Get('v1/communication-config/by-program-type/:programTypeId')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Communication config preview for a program type (new program)' })
  @ApiResponse({ status: HttpStatus.OK })
  async getByProgramType(
    @Param('programTypeId', ParseIntPipe) programTypeId: number,
    @Res() res: Response,
  ): Promise<void> {
    try {
      const data = await this.readService.getByProgramType(programTypeId);
      await this.responseService.success(res, 'Communication config retrieved', data);
    } catch (error) {
      handleControllerError(res, error);
    }
  }

  /**
   * Existing-program state: steps + cloned templates with isEnabled = clone.is_enabled.
   */
  @Get('v1/programs/:programId/communication-config')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Communication config for an existing program' })
  @ApiResponse({ status: HttpStatus.OK })
  async getByProgram(
    @Param('programId', ParseIntPipe) programId: number,
    @Res() res: Response,
  ): Promise<void> {
    try {
      const data = await this.readService.getByProgram(programId);
      await this.responseService.success(res, 'Communication config retrieved', data);
    } catch (error) {
      handleControllerError(res, error);
    }
  }
}
