import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  UseGuards,
  Req,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { DeviceTokenService } from '../../../application/services/device-token.service';
import {
  RegisterDeviceTokenDto,
  UnregisterDeviceTokenDto,
} from '../dto/device-token.dto';

@ApiTags('Device Tokens')
@Controller('device-tokens')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
export class DeviceTokenController {
  constructor(private readonly deviceTokenService: DeviceTokenService) {}

  @Post()
  @ApiOperation({ summary: 'Register device push token (FCM/APNs/HMS/Xiaomi/OPPO/vivo)' })
  async register(@Body() dto: RegisterDeviceTokenDto, @Req() req: any) {
    const token = await this.deviceTokenService.registerToken({
      userId: req.user.id,
      platform: dto.platform,
      channel: dto.channel,
      token: dto.token,
      deviceId: dto.deviceId,
      deviceModel: dto.deviceModel,
      appVersion: dto.appVersion,
    });
    return { code: 0, data: token };
  }

  @Delete()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Unregister device push token' })
  async unregister(@Body() dto: UnregisterDeviceTokenDto) {
    await this.deviceTokenService.unregisterToken(dto.token);
    return { code: 0, data: null };
  }

  @Get()
  @ApiOperation({ summary: 'List active device tokens for current user' })
  async list(@Req() req: any) {
    const tokens = await this.deviceTokenService.getActiveTokens(req.user.id);
    return { code: 0, data: tokens };
  }
}
