import {
  Body,
  Controller,
  Get,
  HttpCode,
  Post,
  Query,
  Request,
  UnauthorizedException,
} from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { FlyerSelectionResponse } from './dto/flyer-selection.response';
import { ReceiptMatchDto } from './dto/receipt-match.dto';
import {
  ReceiptMatchCommitResponse,
  ReceiptMatchPreviewResponse,
} from './dto/receipt-match.response';
import { FlyerSelectionService } from './flyer-selection.service';

@Controller('flyer-selections')
export class FlyerSelectionSyncController {
  constructor(private readonly flyerSelectionService: FlyerSelectionService) {}

  @Get('open')
  @Throttle({ default: { ttl: 60_000, limit: 30 } })
  async listOpen(
    @Query('weekKey') weekKey?: string,
    @Request() req?: any,
  ): Promise<FlyerSelectionResponse[]> {
    const userId = this.getUserId(req);
    return this.flyerSelectionService.listOpen(userId, weekKey);
  }

  @Post('receipt-match-preview')
  @HttpCode(200)
  @Throttle({ default: { ttl: 60_000, limit: 20 } })
  async preview(
    @Body() dto: ReceiptMatchDto,
    @Request() req?: any,
  ): Promise<ReceiptMatchPreviewResponse> {
    const userId = this.getUserId(req);
    return this.flyerSelectionService.previewReceiptMatches(userId, dto);
  }

  @Post('receipt-match-commit')
  @HttpCode(200)
  @Throttle({ default: { ttl: 60_000, limit: 20 } })
  async commit(
    @Body() dto: ReceiptMatchDto,
    @Request() req?: any,
  ): Promise<ReceiptMatchCommitResponse> {
    const userId = this.getUserId(req);
    return this.flyerSelectionService.commitReceiptMatches(userId, dto);
  }

  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;
  }
}
