import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  UseGuards,
} from '@nestjs/common';
import { OidcAuthGuard } from '../../../../libs/auth/src';
import type { AuthenticatedUser } from '../../../../libs/auth/src';
import {
  TripInvitationsService,
  TripMembershipGuard,
  TripRoles,
} from '../../../../libs/trips/src';
import type { TripInvitation, TripMember } from '../../../../libs/trips/src';
import { CurrentUser } from '../auth/current-user.decorator';

interface CreateTripInvitationDto {
  email: string;
}

@Controller()
export class TripInvitationsController {
  constructor(private readonly invitationsService: TripInvitationsService) {}

  @Post('trips/:tripId/invitations')
  @UseGuards(OidcAuthGuard, TripMembershipGuard)
  @TripRoles('OWNER')
  create(
    @Param('tripId') tripId: string,
    @CurrentUser() currentUser: AuthenticatedUser,
    @Body() dto: CreateTripInvitationDto,
  ): Promise<{ invitation: TripInvitation; rawToken: string }> {
    return this.invitationsService.createInvitation(
      tripId,
      currentUser.id,
      dto.email,
    );
  }

  @Get('trips/:tripId/invitations')
  @UseGuards(OidcAuthGuard, TripMembershipGuard)
  @TripRoles('OWNER')
  list(@Param('tripId') tripId: string): Promise<TripInvitation[]> {
    return this.invitationsService.listInvitations(tripId);
  }

  @Delete('trips/:tripId/invitations/:invitationId')
  @UseGuards(OidcAuthGuard, TripMembershipGuard)
  @TripRoles('OWNER')
  remove(
    @Param('tripId') tripId: string,
    @Param('invitationId') invitationId: string,
  ): Promise<void> {
    return this.invitationsService.removeInvitation(tripId, invitationId);
  }

  @Post('invitations/:token/accept')
  @UseGuards(OidcAuthGuard)
  accept(
    @Param('token') token: string,
    @CurrentUser() currentUser: AuthenticatedUser,
  ): Promise<TripMember> {
    return this.invitationsService.acceptInvitation(token, currentUser.id);
  }
}
