package v1

import (
	"quyun/v2/app/http/v1/dto"
	"quyun/v2/app/services"
	"quyun/v2/database/models"

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

// @provider
type Transaction struct{}

// Create Order
//
// @Router /v1/orders [post]
// @Summary Create Order
// @Description Create Order
// @Tags Transaction
// @Accept json
// @Produce json
// @Param form body dto.OrderCreateForm true "Create form"
// @Success 200 {object} dto.OrderCreateResponse
// @Bind user local key(__ctx_user)
// @Bind form body
func (t *Transaction) Create(
	ctx fiber.Ctx,
	user *models.User,
	form *dto.OrderCreateForm,
) (*dto.OrderCreateResponse, error) {
	return services.Order.Create(ctx, user.ID, form)
}

// Pay for order
//
// @Router /v1/orders/:id/pay [post]
// @Summary Pay for order
// @Description Pay for order
// @Tags Transaction
// @Accept json
// @Produce json
// @Param id path string true "Order ID"
// @Param form body dto.OrderPayForm true "Pay form"
// @Success 200 {object} dto.OrderPayResponse
// @Bind user local key(__ctx_user)
// @Bind id path
// @Bind form body
func (t *Transaction) Pay(
	ctx fiber.Ctx,
	user *models.User,
	id string,
	form *dto.OrderPayForm,
) (*dto.OrderPayResponse, error) {
	return services.Order.Pay(ctx, user.ID, id, form)
}

// Check order payment status
//
// @Router /v1/orders/:id/status [get]
// @Summary Check order status
// @Description Check order payment status
// @Tags Transaction
// @Accept json
// @Produce json
// @Param id path string true "Order ID"
// @Success 200 {object} dto.OrderStatusResponse
// @Bind id path
func (t *Transaction) Status(ctx fiber.Ctx, id string) (*dto.OrderStatusResponse, error) {
	return services.Order.Status(ctx, id)
}

type WebhookForm struct {
	OrderID    string `json:"order_id"`
	ExternalID string `json:"external_id"`
}

// Payment Webhook
//
// @Router /v1/webhook/payment/notify [post]
// @Summary Payment Webhook
// @Description Payment Webhook
// @Tags Transaction
// @Accept json
// @Produce json
// @Param form body WebhookForm true "Webhook Data"
// @Success 200 {string} string "success"
// @Bind form body
func (t *Transaction) Webhook(ctx fiber.Ctx, form *WebhookForm) (string, error) {
	err := services.Order.ProcessExternalPayment(ctx, form.OrderID, form.ExternalID)
	if err != nil {
		return "fail", err
	}
	return "success", nil
}
