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 { CreateYardDto } from '../dto/create-yard.dto';
import { MoveOrderDto } from '../dto/move-order.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateYardDto } from '../dto/update-yard.dto';
import { YardsService } from '../services/yards.service';

@ApiTags('yards')
@Controller('yards')
@ApiBearerAuth()
export class YardsController {
  constructor(private readonly service: YardsService) {}

  @Get()
  @RuleEngineView('yards')
  @ApiOperation({ summary: 'List yards' })
  findAll(@Query() query: Record<string, string>) {
    return this.service.findAll({
      isActive: query['isActive'] !== undefined ? query['isActive'] === 'true' : undefined,
      country: query['country'],
      page: query['page'] ? parseInt(query['page'], 10) : undefined,
      pageSize: query['pageSize'] ? parseInt(query['pageSize'], 10) : undefined,
    });
  }

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

  @Post(':id/move-order')
  @RuleEngineManage('yards')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Move a yard 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('yards')
  @ApiOperation({ summary: 'Get a yard by ID' })
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.service.findById(id);
  }

  @Post()
  @RuleEngineManage('yards')
  @ApiOperation({ summary: 'Create a yard' })
  create(@Body() dto: CreateYardDto) {
    return this.service.create(dto);
  }

  @Patch(':id')
  @RuleEngineManage('yards')
  @ApiOperation({ summary: 'Update a yard' })
  update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateYardDto) {
    return this.service.update(id, dto);
  }

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