package controllers

import (
	"encoding/json"

	"github.com/gofiber/fiber/v2"
	"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
	"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
)

// getOSSFromBody creates an OSSProvider from the oss_api_id in the request body.
// If oss_api_id is missing, it falls back to the last active config (legacy behavior).
func getOSSFromBody(c *fiber.Ctx) (services.OSSProvider, error) {
	var req struct {
		OssAPIID *uint `json:"oss_api_id"`
	}
	if err := json.Unmarshal(c.Body(), &req); err != nil {
		req.OssAPIID = nil
	}

	if req.OssAPIID != nil {
		return services.NewOSSProviderByID(*req.OssAPIID)
	}
	return services.NewOSSProviderFromDB()
}

// getOSSFromQuery creates an OSSProvider from the oss_api_id query param.
// If missing, falls back to last active config.
func getOSSFromQuery(c *fiber.Ctx) (services.OSSProvider, error) {
	id := c.QueryInt("oss_api_id", 0)
	if id > 0 {
		return services.NewOSSProviderByID(uint(id))
	}

	lastActive, err := models.GetLastActiveOssApi()
	if err != nil {
		return nil, err
	}
	return services.NewOSSProvider(lastActive)
}
