import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Request,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth } from '@nestjs/swagger';
import { CreateRecurringTransactionDTO } from './dto/create-recurring-transaction.dto';
import { UpdateRecurringTransactionDTO } from './dto/update-recurring-transaction.dto';
import { RecurringTransactionsService } from './recurring-transactions.service';

type AuthenticatedRequest = { user: { id: number } };

@ApiBearerAuth()
@UseGuards(AuthGuard('jwt'))
@Controller({ path: 'recurring-transactions', version: '1' })
export class RecurringTransactionsController {
  constructor(private readonly service: RecurringTransactionsService) {}

  @Get(':teamId')
  getTeamRecurringTransactions(
    @Request() request: AuthenticatedRequest,
    @Param('teamId', ParseIntPipe) teamId: number,
  ) {
    return this.service.getTeamRecurringTransactions(request.user.id, teamId);
  }

  @Post()
  createRecurringTransaction(
    @Request() request: AuthenticatedRequest,
    @Body() dto: CreateRecurringTransactionDTO,
  ) {
    return this.service.createRecurringTransaction(dto, request.user.id);
  }

  @Patch(':id')
  updateRecurringTransaction(
    @Request() request: AuthenticatedRequest,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateRecurringTransactionDTO,
  ) {
    return this.service.updateRecurringTransaction(id, dto, request.user.id);
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  async deleteRecurringTransaction(
    @Request() request: AuthenticatedRequest,
    @Param('id', ParseIntPipe) id: number,
  ): Promise<void> {
    await this.service.deleteRecurringTransaction(id, request.user.id);
  }
}
