import os import uuid from typing import List from fastapi import APIRouter, Depends, HTTPException, status, Query from sqlalchemy.orm import Session from app.auth.dependencies import get_db, get_current_active_user from app.models.user import User from app.models.payment import Payment, PaymentStatus from app.schemas.payment import PaymentInitiate, PaymentResponse, PaystackInitiateResponse router = APIRouter(prefix="/api/payments", tags=["Payments"]) PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "your-paystack-secret-key") PAYSTACK_PUBLIC_KEY = os.getenv("PAYSTACK_PUBLIC_KEY", "your-paystack-public-key") @router.post("/initiate", response_model=PaystackInitiateResponse) def initiate_payment( payment_data: PaymentInitiate, current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db) ): # Generate unique transaction reference transaction_ref = f"URE_{uuid.uuid4().hex[:12].upper()}" # Create payment record db_payment = Payment( user_id=current_user.id, amount=payment_data.amount, transaction_ref=transaction_ref, status=PaymentStatus.PENDING, description=payment_data.description ) db.add(db_payment) db.commit() db.refresh(db_payment) # In a real implementation, you would make an API call to Paystack # For now, we'll return mock data paystack_response = { "authorization_url": f"https://checkout.paystack.com/{transaction_ref}", "access_code": f"access_code_{transaction_ref}", "reference": transaction_ref } return paystack_response @router.post("/verify/{transaction_ref}") def verify_payment( transaction_ref: str, current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db) ): payment = db.query(Payment).filter( Payment.transaction_ref == transaction_ref, Payment.user_id == current_user.id ).first() if not payment: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Payment not found" ) # In a real implementation, you would verify with Paystack API # For now, we'll mark as successful payment.status = PaymentStatus.SUCCESS payment.payment_method = "card" db.commit() return {"message": "Payment verified successfully", "status": "success"} @router.get("/", response_model=List[PaymentResponse]) def get_user_payments( skip: int = Query(0, ge=0), limit: int = Query(50, ge=1, le=100), current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db) ): payments = db.query(Payment).filter( Payment.user_id == current_user.id ).order_by(Payment.created_at.desc()).offset(skip).limit(limit).all() return payments @router.get("/{payment_id}", response_model=PaymentResponse) def get_payment( payment_id: int, current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db) ): payment = db.query(Payment).filter( Payment.id == payment_id, Payment.user_id == current_user.id ).first() if not payment: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Payment not found" ) return payment