package api

import (
	"errors"
	"strings"

	"github.com/ez-api/ez-api/internal/model"
	"gorm.io/gorm"
)

func (h *AdminHandler) revokeMasterByID(id uint) error {
	if id == 0 {
		return gorm.ErrRecordNotFound
	}
	var m model.Master
	if err := h.db.First(&m, id).Error; err != nil {
		return err
	}

	nextEpoch := m.Epoch + 1
	if nextEpoch <= 0 {
		nextEpoch = 1
	}
	if err := h.db.Model(&m).Updates(map[string]any{
		"status": "suspended",
		"epoch":  nextEpoch,
	}).Error; err != nil {
		return err
	}
	if err := h.db.First(&m, id).Error; err != nil {
		return err
	}

	if err := h.db.Model(&model.Key{}).Where("master_id = ?", m.ID).Update("status", "suspended").Error; err != nil {
		return err
	}

	if err := h.syncService.SyncMaster(&m); err != nil {
		return err
	}
	var keys []model.Key
	if err := h.db.Where("master_id = ?", m.ID).Find(&keys).Error; err != nil {
		return err
	}
	for i := range keys {
		if err := h.syncService.SyncKey(&keys[i]); err != nil {
			return err
		}
	}
	return nil
}

func (h *AdminHandler) setMasterStatusByID(id uint, status string) error {
	if id == 0 {
		return gorm.ErrRecordNotFound
	}
	status = strings.ToLower(strings.TrimSpace(status))
	if status == "" {
		return errors.New("status required")
	}
	var m model.Master
	if err := h.db.First(&m, id).Error; err != nil {
		return err
	}
	if err := h.db.Model(&m).Update("status", status).Error; err != nil {
		return err
	}
	if err := h.db.First(&m, id).Error; err != nil {
		return err
	}
	if err := h.syncService.SyncMaster(&m); err != nil {
		return err
	}
	return nil
}

func isRecordNotFound(err error) bool {
	return errors.Is(err, gorm.ErrRecordNotFound)
}
