import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import { PushService } from './push.service';
import { SubscribeDto, UnsubscribeDto, SendNotificationDto } from './push.dto';
import { Public } from '../auth/public.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { UserRole } from '../entities';

@Controller('push')
@UseGuards(RolesGuard)
export class PushController {
  constructor(private readonly pushService: PushService) {}

  @Public()
  @Get('vapid-public-key')
  getVapidPublicKey(): { publicKey: string | null } {
    return { publicKey: this.pushService.getPublicKey() };
  }

  @Public()
  @Post('subscribe')
  @HttpCode(HttpStatus.CREATED)
  async subscribe(@Body() dto: SubscribeDto): Promise<{ success: boolean }> {
    await this.pushService.subscribe(dto);
    return { success: true };
  }

  @Public()
  @Delete('unsubscribe')
  @HttpCode(HttpStatus.NO_CONTENT)
  async unsubscribe(@Body() dto: UnsubscribeDto): Promise<void> {
    await this.pushService.unsubscribe(dto);
  }

  @Roles(UserRole.ADMIN)
  @Get('stats')
  getStats(): Promise<{ totalSubscribers: number }> {
    return this.pushService.getStats();
  }

  @Roles(UserRole.ADMIN, UserRole.CONTRIBUTOR)
  @Post('send')
  @HttpCode(HttpStatus.OK)
  async sendNotification(
    @Body() dto: SendNotificationDto,
  ): Promise<{ sent: number; failed: number }> {
    return this.pushService.sendToAll({
      title: dto.title,
      body: dto.body,
      url: dto.url,
      tag: 'admin-notification',
    });
  }
}
