package entity

import (
	"fmt"
	"strings"
)

// ResetCaption clears the caption when it was generated by the specified source.
// Returns true if the caption changed.
func (m *Photo) ResetCaption(source string) (bool, error) {
	if m == nil {
		return false, fmt.Errorf("photo is nil")
	}

	if !m.HasID() {
		return false, fmt.Errorf("photo id is missing")
	}

	if !m.HasCaption() {
		return false, nil
	}

	src := strings.TrimSpace(strings.ToLower(source))
	current := strings.TrimSpace(strings.ToLower(m.CaptionSrc))

	if src != "" && current != src {
		return false, nil
	}

	updates := Values{
		"PhotoCaption": "",
		"CaptionSrc":   "",
	}

	if err := Db().Model(m).Updates(updates).Error; err != nil {
		return false, err
	}

	m.PhotoCaption = ""
	m.CaptionSrc = ""

	if err := Db().Where("photo_id = ? AND label_src = ?", m.ID, SrcCaption).Delete(&PhotoLabel{}).Error; err != nil {
		return true, err
	}

	if len(m.Labels) > 0 {
		filtered := m.Labels[:0]
		for _, pl := range m.Labels {
			if strings.EqualFold(pl.LabelSrc, SrcCaption) {
				continue
			}
			filtered = append(filtered, pl)
		}
		m.Labels = filtered
	}

	FlushPhotoLabelCache()

	return true, nil
}

// ResetLabels removes labels assigned by the specified source and returns the number of labels removed.
func (m *Photo) ResetLabels(source string) (int64, error) {
	if m == nil {
		return 0, fmt.Errorf("photo is nil")
	}

	if !m.HasID() {
		return 0, fmt.Errorf("photo id is missing")
	}

	src := strings.TrimSpace(strings.ToLower(source))
	if src == "" {
		return 0, nil
	}

	res := Db().Where("photo_id = ? AND label_src = ?", m.ID, src).Delete(&PhotoLabel{})
	if res.Error != nil {
		return 0, res.Error
	}

	if res.RowsAffected > 0 {
		if len(m.Labels) > 0 {
			filtered := m.Labels[:0]
			for _, pl := range m.Labels {
				if strings.EqualFold(strings.ToLower(pl.LabelSrc), src) {
					continue
				}
				filtered = append(filtered, pl)
			}
			m.Labels = filtered
		}
		FlushPhotoLabelCache()
	}

	return res.RowsAffected, nil
}
