import {
  Controller,
  Post,
  Get,
  Body,
  Req,
  Res,
  UseGuards,
  Query,
  BadRequestException,
  Param,
} from '@nestjs/common';
import { PaymentsService } from './payments.service';
import { WebhookService } from './webhook.service';
import { Response } from 'express';
import { Public } from '../auth/public.decorator';
@Controller('payments')
export class PaymentsController {
  constructor(
    private paymentsService: PaymentsService,
    private webhookService: WebhookService,
  ) {}

  @Public()
  @Post('orders')
  async createOrder(@Req() req, @Body() body: any) {
    // If Public, req.user might be missing. Fallback to body.userId or default 1 (System)
    const userId = req.user?.id || body.userId || 1;
    return await this.paymentsService.createOrder(userId, body);
  }

  @Public()
  @Post('success')
  async handleSuccess(@Body() body: any, @Res() res: Response) {
    console.log('PayU Success:', body);
    try {
      await this.webhookService.handlePayUCallback(body);
      return res.redirect(
        `${process.env.FRONTEND_ORIGIN || 'https://jobvumi.com'}/payment/status?status=success`,
      );
    } catch (e) {
      console.error('Payment Verification Failed', e);
      // Debug logging
      try {
        const fs = require('fs');
        const path = require('path');
        const logPath = path.join(process.cwd(), 'payment_errors.log');
        fs.appendFileSync(
          logPath,
          `\n${new Date().toISOString()} - ERROR: ${e.message}\nSTACK: ${e.stack}\nBODY: ${JSON.stringify(body)}\n`,
        );
      } catch (err) {
        console.error('Failed to write log', err);
      }

      return res.redirect(
        `${process.env.FRONTEND_ORIGIN || 'https://jobvumi.com'}/payment/status?status=failed&reason=verification_failed`,
      );
    }
  }

  @Public()
  @Post('failure')
  async handleFailure(@Body() body: any, @Res() res: Response) {
    console.log('PayU Failure:', body);
    try {
      await this.webhookService.handlePayUCallback(body); // Log failure in DB
    } catch (e) {
      console.error('Failure Callback Error', e);
    }
    return res.redirect(
      `${process.env.FRONTEND_ORIGIN || 'https://jobvumi.com'}/payment/status?status=failed`,
    );
  }

  @Public() // Or guarded if needed
  @Get('invoices')
  @Get('invoices')
  async getInvoices(
    @Req() req,
    @Query('limit') limit: any,
    @Query('offset') offset: any,
    @Query('startDate') startDate: any,
    @Query('endDate') endDate: any,
    @Query('status') status: any,
    @Query('userId') userId?: string,
  ) {
    const id = userId ? Number(userId) : req.user?.id ? Number(req.user.id) : 1;
    const limitNum = isNaN(Number(limit)) ? 20 : Number(limit);
    const offsetNum = isNaN(Number(offset)) ? 0 : Number(offset);

    return await this.paymentsService.getInvoices(
      id,
      limitNum,
      offsetNum,
      startDate,
      endDate,
      status,
    );
  }

  @Public()
  @Get('invoice/:id/download')
  async downloadInvoice(@Param('id') id: string, @Res() res: Response) {
    const { buffer, filename } = await this.paymentsService.generateInvoicePdf(
      Number(id),
    );

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': `attachment; filename=${filename}`,
      'Content-Length': buffer.length,
    });

    res.end(buffer);
  }
}
