package service

import (
	"time"

	"github.com/rs/zerolog"

	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/about_us_contents/repository"
)

type aboutUsContentService struct {
	Repo repository.AboutUsContentRepository
	Log  zerolog.Logger
}

type AboutUsContentService interface {
	All() ([]*entity.AboutUsContent, error)
	Show(id uint) (*entity.AboutUsContent, error)
	Save(data *entity.AboutUsContent) (*entity.AboutUsContent, error)
	Update(id uint, data *entity.AboutUsContent) error
	Delete(id uint) error
}

func NewAboutUsContentService(
	repo repository.AboutUsContentRepository,
	log zerolog.Logger,
) AboutUsContentService {
	return &aboutUsContentService{
		Repo: repo,
		Log:  log,
	}
}

// GET ALL
func (s *aboutUsContentService) All() ([]*entity.AboutUsContent, error) {
	results, err := s.Repo.GetAll()
	if err != nil {
		s.Log.Error().Err(err).Msg("failed get about us contents")
		return nil, err
	}

	return results, nil
}

// GET BY ID
func (s *aboutUsContentService) Show(id uint) (*entity.AboutUsContent, error) {
	result, err := s.Repo.FindOne(id)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed get about us content")
		return nil, err
	}

	return result, nil
}

// CREATE
func (s *aboutUsContentService) Save(data *entity.AboutUsContent) (*entity.AboutUsContent, error) {
	result, err := s.Repo.Create(data)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed create about us content")
		return nil, err
	}

	return result, nil
}

// UPDATE
func (s *aboutUsContentService) Update(id uint, data *entity.AboutUsContent) error {
	err := s.Repo.Update(id, data)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed update about us content")
		return err
	}

	return nil
}

// DELETE (soft delete)
func (s *aboutUsContentService) Delete(id uint) error {
	result, err := s.Repo.FindOne(id)
	if err != nil {
		return err
	}

	isActive := false
	result.IsActive = &isActive
	result.UpdatedAt = time.Now()

	return s.Repo.Update(id, result)
}