package repository

import (
	"wails-app/internal/dao"
	"wails-app/internal/global"
)

type MonthlyCardRepository struct{}

func (r *MonthlyCardRepository) Create(card *dao.MonthlyCard) error {
	return global.GVA_DB.Create(card).Error
}

func (r *MonthlyCardRepository) GetByVehicleID(vehicleID uint) (*dao.MonthlyCard, error) {
	var card dao.MonthlyCard
	err := global.GVA_DB.Where("vehicle_id = ? AND payment_status = ?", vehicleID, "paid").Preload("Vehicle").First(&card).Error
	if err != nil {
		return nil, err
	}
	return &card, nil
}

func (r *MonthlyCardRepository) Update(card *dao.MonthlyCard) error {
	return global.GVA_DB.Save(card).Error
}

type MonthlyCardQuery struct {
	PlateNumber string `form:"plate_number"`
	CardType    string `form:"card_type"`
	Page        int    `form:"page"`
	PageSize    int    `form:"page_size"`
}

type MonthlyCardResult struct {
	ID            uint    `json:"id"`
	PlateNumber   string  `json:"plate_number"`
	CardType      string  `json:"card_type"`
	StartDate     string  `json:"start_date"`
	EndDate       string  `json:"end_date"`
	Fee           float64 `json:"fee"`
	PaymentStatus string  `json:"payment_status"`
}

func (r *MonthlyCardRepository) List(q MonthlyCardQuery) ([]MonthlyCardResult, int64, error) {
	db := global.GVA_DB.Table("monthly_card").
		Select("monthly_card.id, vehicle.plate_number, monthly_card.card_type, monthly_card.start_date, monthly_card.end_date, monthly_card.fee, monthly_card.payment_status").
		Joins("LEFT JOIN vehicle ON vehicle.id = monthly_card.vehicle_id")

	if q.PlateNumber != "" {
		db = db.Where("vehicle.plate_number LIKE ?", "%"+q.PlateNumber+"%")
	}
	if q.CardType != "" {
		db = db.Where("monthly_card.card_type = ?", q.CardType)
	}

	var total int64
	db.Count(&total)

	if q.Page <= 0 {
		q.Page = 1
	}
	if q.PageSize <= 0 {
		q.PageSize = 10
	}
	offset := (q.Page - 1) * q.PageSize

	var results []MonthlyCardResult
	err := db.Order("monthly_card.id DESC").Offset(offset).Limit(q.PageSize).Scan(&results).Error
	return results, total, err
}
