package service

import (
	"fmt"
	"time"
	"wails-app/internal/dao"
	"wails-app/internal/global"
	"wails-app/internal/modules/payment/repository"
)

// Payment method constants — add new methods here for POS/Wechat/Alipay
const (
	PaymentCash   = "cash"
	PaymentFree   = "free"
	PaymentPOS    = "pos"
	PaymentWechat = "wechat"
	PaymentAlipay = "alipay"
)

type PaymentService struct {
	repo *repository.PaymentRepository
}

func NewPaymentService() *PaymentService {
	return &PaymentService{repo: &repository.PaymentRepository{}}
}

// ProcessPayment creates a payment_record and updates vehicle_record payment status
func (s *PaymentService) ProcessPayment(recordID uint, paymentMethod string, amount float64, paidAmount float64, operatorID uint) (*dao.PaymentRecord, error) {
	changeAmount := 0.0
	if paymentMethod == PaymentCash && paidAmount > amount {
		changeAmount = paidAmount - amount
	}

	now := time.Now()
	pr := &dao.PaymentRecord{
		RecordID:      recordID,
		PaymentMethod: paymentMethod,
		Amount:        amount,
		PaidAmount:    paidAmount,
		ChangeAmount:  changeAmount,
		OperatorID:    operatorID,
		PaidAt:        now,
	}

	if err := s.repo.Create(pr); err != nil {
		return nil, fmt.Errorf("创建支付记录失败: %w", err)
	}

	// Update vehicle_record payment status
	global.GVA_DB.Model(&dao.VehicleRecord{}).Where("id = ?", recordID).Updates(map[string]interface{}{
		"payment_status": "paid",
		"payment_method": paymentMethod,
	})

	return pr, nil
}

// QueryPayments 查询收费记录列表
func (s *PaymentService) QueryPayments(q repository.PaymentListQuery) ([]repository.PaymentListResult, int64, error) {
	return s.repo.List(q)
}

// GetTodaySummary 获取当日收费汇总
func (s *PaymentService) GetTodaySummary() (repository.TodaySummary, error) {
	return s.repo.GetTodaySummary()
}
