package repository

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

type TicketRepository struct{}

func (r *TicketRepository) Create(ticket *dao.DigitalTicket) error {
	return global.GVA_DB.Create(ticket).Error
}

func (r *TicketRepository) GetByTicketNo(ticketNo string) (*dao.DigitalTicket, error) {
	var t dao.DigitalTicket
	err := global.GVA_DB.Where("ticket_no = ?", ticketNo).First(&t).Error
	if err != nil {
		return nil, err
	}
	return &t, nil
}

func (r *TicketRepository) GetByID(id uint) (*dao.DigitalTicket, error) {
	var t dao.DigitalTicket
	err := global.GVA_DB.First(&t, id).Error
	if err != nil {
		return nil, err
	}
	return &t, nil
}

func (r *TicketRepository) UpdateState(id uint, state string, updates map[string]interface{}) error {
	updates["state"] = state
	return global.GVA_DB.Model(&dao.DigitalTicket{}).Where("id = ?", id).Updates(updates).Error
}

type TicketListQuery struct {
	PlateNumber string `form:"plate_number"`
	State       string `form:"state"`
	Page        int    `form:"page"`
	PageSize    int    `form:"page_size"`
}

func (r *TicketRepository) List(q TicketListQuery) ([]dao.DigitalTicket, int64, error) {
	db := global.GVA_DB.Model(&dao.DigitalTicket{})
	if q.PlateNumber != "" {
		db = db.Where("plate_number LIKE ?", "%"+q.PlateNumber+"%")
	}
	if q.State != "" {
		db = db.Where("state = ?", q.State)
	}
	var total int64
	db.Count(&total)
	if q.Page <= 0 {
		q.Page = 1
	}
	if q.PageSize <= 0 {
		q.PageSize = 10
	}
	var list []dao.DigitalTicket
	err := db.Order("id DESC").Offset((q.Page - 1) * q.PageSize).Limit(q.PageSize).Find(&list).Error
	return list, total, err
}
