import { Body, Controller, HttpCode, HttpStatus, Logger, Post, } from '@nestjs/common';
import { TelebirrWebhookService } from './providers/telebirr.service';
import { ApiOperation } from '@nestjs/swagger';
import { TelebirrDto } from './dto/telebirr.dto';
import { Public } from '@edr/api-common';

@Controller("payments-webhooks")
@Public()
export class WebhookController {
    constructor(private readonly telebirr: TelebirrWebhookService) { }
    private readonly logger = new Logger(WebhookController.name);

    @Post('telebirr')
    @HttpCode(HttpStatus.OK)
    @ApiOperation({
        summary: 'Telebirr payment notification callback (Ethiopia)',
        description: 'Webhook endpoint for Telebirr payment status updates. Used by Ethiopian passengers.'
    })
    async receiveTelebirr(@Body() payload: TelebirrDto) {
        this.logger.log(
            `Telebirr webhook Called`,
        );

        try {
            const verified = this.telebirr.verifyTelebirrNotification(payload)
            if (!verified) {
                throw new Error("Telebirr webhook signature verification failed")
            }
            await this.telebirr.handle(payload);

        } catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            this.logger.error(`Telebirr webhook handler threw: ${message}`);
        }
        return { code: '0', message: 'OK' };
    }

}
