import {
  Controller,
  Get,
  Param,
  ParseIntPipe,
  Patch,
  Request,
  UnauthorizedException,
  Body,
} from '@nestjs/common';
import { ShoppingListService } from './shopping-list.service';
import { UpdateShoppingListItemStatusDto } from './dto/update-shopping-list-item-status.dto';
import { ShoppingListItemResponse } from './dto/shopping-list-item.response';

@Controller('shopping-list')
export class ShoppingListController {
  constructor(private readonly shoppingListService: ShoppingListService) {}

  @Get('items')
  async listOpen(@Request() req?: any): Promise<ShoppingListItemResponse[]> {
    const userId = this.getUserId(req);
    return this.shoppingListService.listOpen(userId);
  }

  @Patch('items/:itemId/status')
  async updateStatus(
    @Param('itemId', ParseIntPipe) itemId: number,
    @Body() dto: UpdateShoppingListItemStatusDto,
    @Request() req?: any,
  ): Promise<ShoppingListItemResponse> {
    const userId = this.getUserId(req);
    return this.shoppingListService.updateCheckedStatus(userId, itemId, dto.checked);
  }

  private getUserId(req?: any): number {
    const userId =
      typeof req?.user?.id === 'number'
        ? req.user.id
        : typeof req?.user?.userId === 'number'
          ? req.user.userId
          : undefined;

    if (!userId) {
      throw new UnauthorizedException('Kunde inte identifiera användaren.');
    }

    return userId;
  }
}
