import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, Query } from '@nestjs/common';
import { PantryService } from './pantry.service';
import { CreatePantryItemDto } from './dto/create-pantry-item.dto';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { Roles } from '../auth/decorators/roles.decorator';
import { CreateInventoryDto } from '../inventory/dto/create-inventory.dto';
import { CreateAdminPantryItemDto } from './dto/create-admin-pantry-item.dto';
import { UpdatePantryItemDto } from './dto/update-pantry-item.dto';

@Controller('pantry')
export class PantryController {
  constructor(private readonly pantryService: PantryService) {}

  @Get()
  findAll(@CurrentUser() user: { userId: number }) {
    return this.pantryService.findAll(user.userId);
  }

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

  @Roles('admin')
  @Get('admin')
  findAllAdmin(@Query('userId') userIdRaw?: string) {
    const userId = userIdRaw == null || userIdRaw.trim() === '' ? undefined : Number(userIdRaw);
    return this.pantryService.findAllAdmin({
      userId: Number.isFinite(userId as number) ? (userId as number) : undefined,
    });
  }

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

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

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

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

  @Post(':id/move-to-inventory')
  moveToInventory(
    @CurrentUser() user: { userId: number },
    @Param('id', ParseIntPipe) id: number,
    @Body() body: CreateInventoryDto,
  ) {
    return this.pantryService.moveToInventory(user.userId, id, body);
  }

  @Roles('admin')
  @Post('admin/:id/move-to-inventory')
  moveToInventoryAdmin(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: CreateInventoryDto,
  ) {
    return this.pantryService.moveToInventoryAdmin(id, body);
  }
}
