package repository

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

type ShiftRepository struct{}

func (r *ShiftRepository) Create(record *dao.ShiftRecord) error {
	return global.GVA_DB.Create(record).Error
}

func (r *ShiftRepository) Update(record *dao.ShiftRecord) error {
	return global.GVA_DB.Save(record).Error
}

func (r *ShiftRepository) GetActive(operatorID uint) (*dao.ShiftRecord, error) {
	var s dao.ShiftRecord
	err := global.GVA_DB.Where("operator_id = ? AND status = ?", operatorID, "active").First(&s).Error
	if err != nil {
		return nil, err
	}
	return &s, nil
}

type ShiftListQuery struct {
	Page     int  `form:"page"`
	PageSize int  `form:"page_size"`
	ShowAll  bool `form:"show_all"`
}

type ShiftListItem struct {
	dao.ShiftRecord
	OperatorName string `json:"operator_name"`
}

func (r *ShiftRepository) List(q ShiftListQuery, operatorID uint) ([]ShiftListItem, int64, error) {
	db := global.GVA_DB.Table("shift_record sr").
		Select("sr.*, su.nick_name as operator_name").
		Joins("LEFT JOIN sys_users su ON su.id = sr.operator_id")

	if !q.ShowAll {
		db = db.Where("sr.operator_id = ?", operatorID)
	}

	var total int64
	db.Count(&total)

	if q.Page <= 0 {
		q.Page = 1
	}
	if q.PageSize <= 0 {
		q.PageSize = 20
	}
	var list []ShiftListItem
	err := db.Order("sr.id DESC").Offset((q.Page - 1) * q.PageSize).Limit(q.PageSize).Scan(&list).Error
	return list, total, err
}
