package routes

import (
	"time"

	"lune/talentscale/internal/middleware"
	"lune/talentscale/internal/modules/billing/handlers"

	"github.com/gofiber/fiber/v2"
)

// BillingRouteConfig holds all dependencies needed for billing routes
type BillingRouteConfig struct {
	App               *fiber.App
	JWTSecret         string
	RoleRepo          interface {
		GetPermissionsByRoleID(ctx interface{}, roleID interface{}) (interface{}, error)
	}
	CheckoutHandler   *handlers.CheckoutHandler
	InvoiceHandler    *handlers.InvoiceHandler
	SubscriptionHandler *handlers.SubscriptionHandler
	PackageHandler    *handlers.PackageHandler
	WebhookHandler    *handlers.WebhookHandler
	RateLimitEnabled  bool
}

// RegisterBillingRoutes registers all billing-related routes
func RegisterBillingRoutes(
	router fiber.Router,
	jwtSecret string,
	checkoutH *handlers.CheckoutHandler,
	invoiceH *handlers.InvoiceHandler,
	subscriptionH *handlers.SubscriptionHandler,
	packageH *handlers.PackageHandler,
	webhookH *handlers.WebhookHandler,
	rateLimitEnabled bool,
) {
	auth := middleware.AuthMiddleware(jwtSecret)
	tenant := middleware.TenantMiddleware()

	// ─── Public Routes (No Auth) ─────────────────────────────────────────────
	public := router.Group("/public")

	// GET /api/v1/public/billing/packages — cached package list
	public.Get("/billing/packages", packageH.ListPublicPackages)

	// POST /api/v1/public/payments/midtrans/webhook — idempotent webhook
	if rateLimitEnabled {
		public.Post("/payments/midtrans/webhook",
			middleware.RateLimiter(100, 1*time.Minute, "webhook"),
			webhookH.HandleMidtransWebhook,
		)
	} else {
		public.Post("/payments/midtrans/webhook", webhookH.HandleMidtransWebhook)
	}

	// ─── Client Routes (Authenticated + Tenant) ──────────────────────────────
	client := router.Group("/client/billing", auth, tenant)

	// POST /api/client/billing/checkout
	client.Post("/checkout", checkoutH.Checkout)

	// POST /api/client/billing/retry
	client.Post("/retry", checkoutH.RetryPayment)

	// GET /api/client/billing/invoices
	client.Get("/invoices", invoiceH.ListInvoices)

	// GET /api/client/billing/invoices/:id
	client.Get("/invoices/:id", invoiceH.GetInvoiceDetail)

	// GET /api/client/billing/subscription
	client.Get("/subscription", subscriptionH.GetActive)
}
