import {
  Body, Controller, Delete, Get, HttpCode, HttpStatus,
  Param, ParseUUIDPipe, Patch, Post, Query,
} from '@nestjs/common';
import { RuleEngineManage, RuleEngineView } from '../../../common/rule-engine-guards';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateServiceTypeDto } from '../dto/create-service-type.dto';
import { MoveOrderDto } from '../dto/move-order.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateServiceTypeDto } from '../dto/update-service-type.dto';
import { ServiceTypesService } from '../services/service-types.service';

@ApiTags('service-types')
@Controller('service-types')
@ApiBearerAuth()
export class ServiceTypesController {
  constructor(private readonly service: ServiceTypesService) {}

  @Get()
  @RuleEngineView('service-types')
  @ApiOperation({ summary: 'List service types' })
  findAll(@Query() query: Record<string, string>) {
    return this.service.findAll({
      isActive: query['isActive'] !== undefined ? query['isActive'] === 'true' : undefined,
      canBeBookedAlone: query['canBeBookedAlone'] !== undefined ? query['canBeBookedAlone'] === 'true' : undefined,
      search: query['search'],
      page: query['page'] ? parseInt(query['page'], 10) : undefined,
      pageSize: query['pageSize'] ? parseInt(query['pageSize'], 10) : undefined,
      sortBy: query['sortBy'],
      sortOrder: (query['sortOrder'] as 'ASC' | 'DESC') ?? 'ASC',
    });
  }

  @Post('reorder')
  @RuleEngineManage('service-types')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Bulk reorder service types by ID list' })
  reorder(@Body() dto: ReorderItemsDto) {
    return this.service.reorder(dto);
  }

  @Post(':id/move-order')
  @RuleEngineManage('service-types')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Move a service type up or down in display order' })
  moveOrder(@Param('id', ParseUUIDPipe) id: string, @Body() dto: MoveOrderDto) {
    return this.service.moveOrder(id, dto.direction);
  }

  @Get(':id')
  @RuleEngineView('service-types')
  @ApiOperation({ summary: 'Get a service type by ID' })
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.service.findById(id);
  }

  @Post()
  @RuleEngineManage('service-types')
  @ApiOperation({ summary: 'Create a service type' })
  create(@Body() dto: CreateServiceTypeDto) {
    return this.service.create(dto);
  }

  @Patch(':id')
  @RuleEngineManage('service-types')
  @ApiOperation({ summary: 'Update a service type' })
  update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateServiceTypeDto) {
    return this.service.update(id, dto);
  }

  @Delete(':id')
  @RuleEngineManage('service-types')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Soft-delete a service type' })
  remove(@Param('id', ParseUUIDPipe) id: string) {
    return this.service.remove(id);
  }
}
