import {
  BadRequestException,
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { CreateInventoryDto } from './dto/create-inventory.dto';
import { UpdateInventoryDto } from './dto/update-inventory.dto';
import { InventoryService } from './inventory.service';
import { ConsumeInventoryDto } from './dto/consume-inventory.dto';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { Roles } from '../auth/decorators/roles.decorator';
import { MergeInventoryDto } from './dto/merge-inventory.dto';
import { CreateAdminInventoryDto } from './dto/create-admin-inventory.dto';
import { BulkDeleteInventoryDto } from './dto/bulk-delete-inventory.dto';
import { MergeManyInventoryDto } from './dto/merge-many-inventory.dto';

@Controller('inventory')
export class InventoryController {
  constructor(private readonly inventoryService: InventoryService) {}

  @Roles('admin')
  @Get('admin')
  findAllAdmin(
    @Query('userId') userIdRaw?: string,
    @Query('sort') sort?: string,
  ) {
    const userId = this.parseOptionalIntQuery(userIdRaw);
    return this.inventoryService.findAllAdmin({
      userId,
      sort,
    });
  }

  private parseOptionalIntQuery(value: string | undefined): number | undefined {
    if (value === undefined || value === null) {
      return undefined;
    }

    const trimmed = value.trim();
    if (trimmed.length === 0) {
      return undefined;
    }

    if (!/^\d+$/.test(trimmed)) {
      throw new BadRequestException('Validation failed (numeric string is expected)');
    }

    return Number(trimmed);
  }

  @Roles('admin')
  @Post('admin')
  createAdmin(
    @CurrentUser() user: { userId: number },
    @Body() body: CreateAdminInventoryDto,
  ) {
    return this.inventoryService.createAdmin(user.userId, body, body.userId);
  }

  @Roles('admin')
  @Patch('admin/:id')
  updateAdmin(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: UpdateInventoryDto,
  ) {
    return this.inventoryService.updateAdmin(id, body);
  }

  @Roles('admin')
  @Delete('admin/:id')
  removeAdmin(@Param('id', ParseIntPipe) id: number) {
    return this.inventoryService.removeAdmin(id);
  }

  @Roles('admin')
  @Post('admin/merge')
  mergeAdmin(@Body() body: MergeInventoryDto) {
    return this.inventoryService.mergeAdmin(
      body.sourceInventoryId,
      body.targetInventoryId,
    );
  }

  @Roles('admin')
  @Get('admin/merge-preview')
  previewMergeAdmin(
    @Query('sourceInventoryId', ParseIntPipe) sourceInventoryId: number,
    @Query('targetInventoryId', ParseIntPipe) targetInventoryId: number,
  ) {
    return this.inventoryService.previewMergeAdmin(
      sourceInventoryId,
      targetInventoryId,
    );
  }

  @Post('merge-many')
  mergeMany(
    @CurrentUser() user: { userId: number },
    @Body() body: MergeManyInventoryDto,
  ) {
    return this.inventoryService.mergeMany(user.userId, body.ids, body.targetUnit);
  }

  @Post('bulk-delete')
  bulkDelete(
    @CurrentUser() user: { userId: number },
    @Body() body: BulkDeleteInventoryDto,
  ) {
    return this.inventoryService.bulkDelete(user.userId, body.ids);
  }
 
 @Post(':id/consume')
 consume(
   @CurrentUser() user: { userId: number },
   @Param('id', ParseIntPipe) id: number,
   @Body() body: ConsumeInventoryDto,
  ) {
  return this.inventoryService.consume(id, user.userId, body);
  }
  
  @Get(':id/consumption-history')
findConsumptionHistory(
  @CurrentUser() user: { userId: number },
  @Param('id', ParseIntPipe) id: number,
) {
  return this.inventoryService.findConsumptionHistory(id, user.userId);
  } 
 
  @Get()
  findAll(
    @CurrentUser() user: { userId: number },
    @Query('location') location?: string,
    @Query('sort') sort?: string,
  ) {
    return this.inventoryService.findAll(user.userId, { location, sort });
  }

  @Get('expiring')
  findExpiring(@CurrentUser() user: { userId: number }) {
    return this.inventoryService.findExpiring(user.userId);
  }

  @Post()
  create(
    @CurrentUser() user: { userId: number },
    @Body() body: CreateInventoryDto,
  ) {
    return this.inventoryService.create(user.userId, body);
  }

  @Patch(':id')
  update(
    @CurrentUser() user: { userId: number },
    @Param('id', ParseIntPipe) id: number,
    @Body() body: UpdateInventoryDto,
  ) {
    return this.inventoryService.update(id, user.userId, body);
  }

  @Delete(':id')
  remove(
    @CurrentUser() user: { userId: number },
    @Param('id', ParseIntPipe) id: number,
  ) {
    return this.inventoryService.remove(id, user.userId);
  }

  @Post(':id/move-to-pantry')
  moveToPantry(
    @CurrentUser() user: { userId: number },
    @Param('id', ParseIntPipe) id: number,
  ) {
    return this.inventoryService.moveToPantry(id, user.userId);
  }

  @Roles('admin')
  @Post('admin/:id/move-to-pantry')
  moveToPantryAdmin(@Param('id', ParseIntPipe) id: number) {
    return this.inventoryService.moveToPantryAdmin(id);
  }
}