import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  Res,
  HttpStatus,
  HttpCode,
  UseGuards,
  ParseIntPipe,
} from '@nestjs/common';
import { Response } from 'express';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiQuery,
  ApiBearerAuth,
  ApiSecurity,
  ApiParam,
} from '@nestjs/swagger';
import { MasterFormSectionService } from './master-form-section.service';
import { CreateMasterFormSectionDto } from './dto/create-master-form-section.dto';
import { UpdateMasterFormSectionDto } from './dto/update-master-form-section.dto';
import { FilterMasterFormSectionDto } from './dto/filter-master-form-section.dto';
import { ResponseService } from 'src/common/response-handling/response-handler';
import { Roles } from 'src/common/decorators/roles.decorator';
import { RolesGuard } from 'src/common/guards/roles.guard';
import { AppLoggerService } from 'src/common/services/logger.service';
import { handleControllerError } from 'src/common/utils/controller-response-handling';
import { CombinedAuthGuard } from 'src/auth/combined-auth.guard';
import { ROLE_VALUES } from 'src/common/constants/strings-constants';

@ApiTags('master-form-section')
@Controller('v1/master-sections')
@UseGuards(CombinedAuthGuard, RolesGuard)
@Roles(ROLE_VALUES.ADMIN, ROLE_VALUES.COORDINATOR)
@ApiBearerAuth('Authorization')
@ApiSecurity('userIdAuth')
@ApiSecurity('activeRoleAuth')
export class MasterFormSectionController {
  constructor(
    private readonly masterFormSectionService: MasterFormSectionService,
    private readonly responseService: ResponseService,
    private readonly logger: AppLoggerService,
  ) {}

  /**
   * Get all master form sections with filters
   */
  @Get()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Get all master form sections with filters' })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  @ApiQuery({ name: 'offset', required: false, type: Number })
  @ApiQuery({ name: 'searchText', required: false, type: String })
  @ApiQuery({ name: 'isActive', required: false, type: Boolean })
  @ApiQuery({ name: 'parentSectionId', required: false, type: Number })
  @ApiResponse({ status: HttpStatus.OK, description: 'Master form sections retrieved successfully' })
  @ApiResponse({ status: HttpStatus.INTERNAL_SERVER_ERROR, description: 'Internal server error' })
  async findAll(@Query() filters: FilterMasterFormSectionDto, @Res() res: Response) {
    this.logger.log('GET /v1/master-sections - Request received', { filters });
    try {
      const result = await this.masterFormSectionService.findAll(filters);
      this.logger.log('Master form sections retrieved successfully');
      return this.responseService.success(res, 'Master form sections retrieved successfully', result);
    } catch (error) {
      handleControllerError(res, error);
    }
  }

  /**
   * Get section hierarchy (tree structure)
   */
  @Get('hierarchy')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Get master form sections as hierarchical tree' })
  @ApiResponse({ status: HttpStatus.OK, description: 'Section hierarchy retrieved successfully' })
  @ApiResponse({ status: HttpStatus.INTERNAL_SERVER_ERROR, description: 'Internal server error' })
  async getHierarchy(@Res() res: Response) {
    this.logger.log('GET /v1/master-sections/hierarchy - Request received');
    try {
      const result = await this.masterFormSectionService.getHierarchy();
      this.logger.log('Section hierarchy retrieved successfully');
      return this.responseService.success(res, 'Section hierarchy retrieved successfully', result);
    } catch (error) {
      handleControllerError(res, error);
    }
  }

  /**
   * Get a single master form section by ID
   */
  @Get(':id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Get a master form section by ID' })
  @ApiParam({ name: 'id', type: Number, description: 'Master form section ID' })
  @ApiResponse({ status: HttpStatus.OK, description: 'Master form section retrieved successfully' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Master form section not found' })
  @ApiResponse({ status: HttpStatus.INTERNAL_SERVER_ERROR, description: 'Internal server error' })
  async findById(@Param('id', ParseIntPipe) id: number, @Res() res: Response) {
    this.logger.log('GET /v1/master-sections/:id - Request received', { id });
    try {
      const result = await this.masterFormSectionService.findById(id);
      this.logger.log('Master form section retrieved successfully');
      return this.responseService.success(res, 'Master form section retrieved successfully', result);
    } catch (error) {
      handleControllerError(res, error);
    }
  }

  /**
   * Get subsections of a section
   */
  @Get(':id/subsections')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Get subsections of a master form section' })
  @ApiParam({ name: 'id', type: Number, description: 'Parent section ID' })
  @ApiResponse({ status: HttpStatus.OK, description: 'Subsections retrieved successfully' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Parent section not found' })
  @ApiResponse({ status: HttpStatus.INTERNAL_SERVER_ERROR, description: 'Internal server error' })
  async getChildren(@Param('id', ParseIntPipe) id: number, @Res() res: Response) {
    this.logger.log('GET /v1/master-sections/:id/subsections - Request received', { id });
    try {
      const result = await this.masterFormSectionService.getChildren(id);
      this.logger.log('Section subsections retrieved successfully');
      return this.responseService.success(res, 'Section subsections retrieved successfully', result);
    } catch (error) {
      handleControllerError(res, error);
    }
  }


  /**
   * Create a new master form section
   */
  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Create a new master form section' })
  @ApiResponse({ status: HttpStatus.CREATED, description: 'Master form section created successfully' })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: 'Bad request' })
  @ApiResponse({ status: HttpStatus.INTERNAL_SERVER_ERROR, description: 'Internal server error' })
  async create(@Body() createDto: CreateMasterFormSectionDto, @Res() res: Response) {
    this.logger.log('POST /v1/master-sections - Request received', { createDto });
    try {
      const result = await this.masterFormSectionService.create(createDto);
      this.logger.log('Master form section created successfully');
      return this.responseService.success(res, 'Master form section created successfully', result, HttpStatus.CREATED);
    } catch (error) {
      handleControllerError(res, error);
    }
  }

  /**
   * Update a master form section
   */
  @Put(':id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Update a master form section' })
  @ApiParam({ name: 'id', type: Number, description: 'Master form section ID' })
  @ApiResponse({ status: HttpStatus.OK, description: 'Master form section updated successfully' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Master form section not found' })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: 'Bad request' })
  @ApiResponse({ status: HttpStatus.INTERNAL_SERVER_ERROR, description: 'Internal server error' })
  async update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateDto: UpdateMasterFormSectionDto,
    @Res() res: Response,
  ) {
    this.logger.log('PUT /v1/master-sections/:id - Request received', { id, updateDto });
    try {
      const result = await this.masterFormSectionService.update(id, updateDto);
      this.logger.log('Master form section updated successfully');
      return this.responseService.success(res, 'Master form section updated successfully', result ?? undefined);
    } catch (error) {
      handleControllerError(res, error);
    }
  }

  /**
   * Soft delete a master form section
   */
  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Delete a master form section' })
  @ApiParam({ name: 'id', type: Number, description: 'Master form section ID' })
  @ApiResponse({ status: HttpStatus.OK, description: 'Master form section deleted successfully' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Master form section not found' })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: 'Cannot delete section with subsections' })
  @ApiResponse({ status: HttpStatus.INTERNAL_SERVER_ERROR, description: 'Internal server error' })
  async delete(@Param('id', ParseIntPipe) id: number, @Res() res: Response) {
    this.logger.log('DELETE /v1/master-sections/:id - Request received', { id });
    try {
      await this.masterFormSectionService.delete(id);
      this.logger.log('Master form section deleted successfully');
      return this.responseService.success(res, 'Master form section deleted successfully', { id });
    } catch (error) {
      handleControllerError(res, error);
    }
  }
}
