import { Controller, Post, Req, HttpCode, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { Public } from '../../../common/decorators/public.decorator';
import { AppStoreNotificationService } from './app-store-notification.service';

/**
 * M-MEMBER-01-06: App Store Server Notifications V2 Webhook
 *
 * POST /webhooks/app-store/v2
 * @Public — 无需用户 Bearer Token。Apple 直接回调。
 */
@Public()
@ApiTags('webhooks')
@Controller('webhooks/app-store')
export class AppStoreNotificationController {
  private readonly logger = new Logger(AppStoreNotificationController.name);

  constructor(private readonly service: AppStoreNotificationService) {}

  @Post('v2')
  @HttpCode(200)
  @ApiOperation({ summary: 'App Store Server Notification V2（Apple 回调）' })
  async handleNotification(@Req() req: any) {
    const signedPayload = req.body?.signedPayload;
    if (!signedPayload) {
      this.logger.warn('App Store notification missing signedPayload');
      return { ok: true }; // 快速 200 避免 Apple 重试
    }

    // 异步处理——不阻塞 200 响应
    this.service.processNotification(signedPayload).catch((err) => {
      this.logger.error(`Async notification processing failed: ${err?.message ?? err}`);
    });

    return { ok: true };
  }
}
