import { Body, Controller, Get, Param, ParseUUIDPipe, Patch, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';

import { BookingStaff } from '../../common/booking-guards';
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
import { CreateWarehouseZoneDto } from './dto/create-warehouse-zone.dto';
import { UpdateWarehouseYardDto } from './dto/update-warehouse-yard.dto';
import { WarehouseYardsService } from './warehouse-yards.service';
import { WarehouseZonesService } from './warehouse-zones.service';

@ApiTags('warehouse-yards')
@ApiBearerAuth()
// No class-level guard: every route carries its own permission (reads accept
// yard-view OR inventory-view so inventory flows can populate yard pickers).
@Controller('warehouse-yards')
export class WarehouseYardsController {
  constructor(
    private readonly yardsService: WarehouseYardsService,
    private readonly zonesService: WarehouseZonesService,
  ) {}

  @Get()
  @BookingStaff([FREIGHT_PERMS.warehouseYards.view, FREIGHT_PERMS.warehouseInventory.view])
  @ApiOperation({ summary: 'List all warehouse yards' })
  findAll() {
    return this.yardsService.findAll();
  }

  @Get(':id')
  @BookingStaff([FREIGHT_PERMS.warehouseYards.view, FREIGHT_PERMS.warehouseInventory.view])
  @ApiOperation({ summary: 'Get warehouse yard by ID' })
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.yardsService.findById(id);
  }

  @Patch(':id')
  @BookingStaff(FREIGHT_PERMS.warehouseYards.update)
  @ApiOperation({ summary: 'Update warehouse yard' })
  update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateWarehouseYardDto) {
    return this.yardsService.update(id, dto);
  }

  @Get(':yardId/zones')
  @BookingStaff(FREIGHT_PERMS.warehouseZones.view)
  @ApiOperation({ summary: 'List zones within a yard' })
  listZones(@Param('yardId', ParseUUIDPipe) yardId: string) {
    return this.zonesService.findByYard(yardId);
  }

  @Post(':yardId/zones')
  @BookingStaff(FREIGHT_PERMS.warehouseZones.create)
  @ApiOperation({ summary: 'Create a zone within a yard' })
  createZone(
    @Param('yardId', ParseUUIDPipe) yardId: string,
    @Body() dto: CreateWarehouseZoneDto,
  ) {
    return this.zonesService.create(yardId, dto);
  }
}
