import {
  Body,
  Controller,
  Get,
  Query,
  Req,
  Put,
  UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { UserRole } from '@prisma/client';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { Permissions } from '../../common/decorators/permissions.decorator';
import { PermissionsGuard } from '../../common/guards/permissions.guard';
import { UpsertLoyaltySettingsDto } from './dto/upsert-loyalty-settings.dto';
import { LoyaltySettingsService } from './loyalty-settings.service';

type RequestWithUser = {
  user: {
    id: string;
    role: UserRole;
    shopId: string | null;
  };
};

@ApiTags('loyalty')
@ApiBearerAuth()
@Controller('loyalty')
@UseGuards(JwtAuthGuard, RolesGuard, PermissionsGuard)
@Roles(UserRole.SUPERADMIN, UserRole.ADMIN, UserRole.SUBADMIN)
@Permissions('loyalty')
export class LoyaltySettingsController {
  constructor(private readonly loyalty: LoyaltySettingsService) {}

  @Get('settings')
  @ApiOkResponse({
    description:
      'Get loyalty settings for current shop (or shopId if SUPERADMIN)',
  })
  get(@Req() req: RequestWithUser, @Query('shopId') shopId?: string) {
    if (shopId) return this.loyalty.getByShopId(req.user, shopId);
    return this.loyalty.getForCurrentShop(req.user);
  }

  @Put('settings')
  @ApiOkResponse({ description: 'Upsert loyalty settings for current shop' })
  upsert(
    @Req() req: RequestWithUser,
    @Body() dto: UpsertLoyaltySettingsDto,
    @Query('shopId') shopId?: string,
  ) {
    if (shopId) return this.loyalty.upsertByShopId(req.user, shopId, dto);
    return this.loyalty.upsertForCurrentShop(req.user, dto);
  }
}
