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

@ApiTags('cargo-types')
@Controller('cargo-types')
@ApiBearerAuth()
export class CargoTypesController {
  constructor(private readonly service: CargoTypesService) {}

  @Get()
  @RuleEngineView('cargo-types')
  @ApiOperation({ summary: 'List cargo types' })
  findAll(@Query() query: Record<string, string>) {
    return this.service.findAll({
      isActive: query['isActive'] !== undefined ? query['isActive'] === 'true' : undefined,
      requiresDirectorApproval: query['requiresDirectorApproval'] !== undefined
        ? query['requiresDirectorApproval'] === 'true'
        : undefined,
      parentGroupId: query['parentGroupId'],
      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('cargo-types')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Bulk reorder cargo types by ID list' })
  reorder(@Body() dto: ReorderItemsDto) {
    return this.service.reorder(dto);
  }

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

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

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

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