import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  ParseUUIDPipe,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiParam,
} from '@nestjs/swagger';
import { TradeEventsService } from './trade-events.service';
import { CreateTradeEventDto } from './dto/create-trade-event.dto';
import { UpdateTradeEventDto } from './dto/update-trade-event.dto';
import { CurrentUser, JwtPayload } from '../common/decorators';
import { TenantGuard } from '../auth/guards/tenant.guard';
import { singleResponse } from '../common/dto/pagination.dto';

@ApiTags('TradeEvents')
@ApiBearerAuth('access-token')
@UseGuards(TenantGuard)
@Controller('trade-events')
export class TradeEventsController {
  constructor(private readonly tradeEventsService: TradeEventsService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Messe-Event erstellen' })
  async create(
    @CurrentUser() user: JwtPayload,
    @Body() dto: CreateTradeEventDto,
  ) {
    const event = await this.tradeEventsService.create(
      user.tenantId!,
      user.sub,
      dto,
    );
    return singleResponse(event);
  }

  @Get()
  @ApiOperation({ summary: 'Alle Messe-Events auflisten' })
  async findAll(@CurrentUser() user: JwtPayload) {
    const events = await this.tradeEventsService.findAll(user.tenantId!);
    return { data: events };
  }

  // WICHTIG: /active muss VOR /:id stehen, sonst wird "active" als UUID geparst
  @Get('active')
  @ApiOperation({ summary: 'Aktive Messe-Events fuer Dashboard' })
  async findActive(@CurrentUser() user: JwtPayload) {
    const events = await this.tradeEventsService.findActive(user.tenantId!);
    return { data: events };
  }

  @Get(':id')
  @ApiOperation({ summary: 'Messe-Event abrufen' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async findOne(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    const event = await this.tradeEventsService.findOne(
      user.tenantId!,
      id,
    );
    return singleResponse(event);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Messe-Event aktualisieren' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async update(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: UpdateTradeEventDto,
  ) {
    const event = await this.tradeEventsService.update(
      user.tenantId!,
      id,
      user.sub,
      dto,
    );
    return singleResponse(event);
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Messe-Event loeschen' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async remove(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    const event = await this.tradeEventsService.remove(
      user.tenantId!,
      id,
    );
    return singleResponse(event);
  }
}
