package repository

import (
	"github.com/rs/zerolog"

	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
)

type aboutUsContentRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

// interface
type AboutUsContentRepository interface {
	GetAll() ([]*entity.AboutUsContent, error)
	FindOne(id uint) (*entity.AboutUsContent, error)
	Create(data *entity.AboutUsContent) (*entity.AboutUsContent, error)
	Update(id uint, data *entity.AboutUsContent) error
	Delete(id uint) error
}

// constructor
func NewAboutUsContentRepository(db *database.Database, logger zerolog.Logger) AboutUsContentRepository {
	return &aboutUsContentRepository{
		DB:  db,
		Log: logger,
	}
}

// GET ALL
func (r *aboutUsContentRepository) GetAll() ([]*entity.AboutUsContent, error) {
	var results []*entity.AboutUsContent

	err := r.DB.DB.
		Preload("Images").
		Where("is_active IS NULL OR is_active = ?", true).
		Order("id ASC").
		Find(&results).Error

	if err != nil {
		r.Log.Error().Err(err).Msg("failed get about us contents")
		return nil, err
	}

	return results, nil
}

// GET ONE
func (r *aboutUsContentRepository) FindOne(id uint) (*entity.AboutUsContent, error) {
	var data entity.AboutUsContent

	err := r.DB.DB.First(&data, id).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed find about us content")
		return nil, err
	}

	return &data, nil
}

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

	return data, nil
}

// Update uses a column map so we never SET primary key / created_at to zero values (breaks FK children).
func (r *aboutUsContentRepository) Update(id uint, data *entity.AboutUsContent) error {
	updates := map[string]interface{}{
		"primary_title":        data.PrimaryTitle,
		"secondary_title":      data.SecondaryTitle,
		"description":          data.Description,
		"primary_cta":          data.PrimaryCta,
		"secondary_cta_text":   data.SecondaryCtaText,
		"updated_at":           data.UpdatedAt,
	}
	if data.IsActive != nil {
		updates["is_active"] = data.IsActive
	}

	err := r.DB.DB.
		Model(&entity.AboutUsContent{}).
		Where("id = ?", id).
		Updates(updates).Error

	if err != nil {
		r.Log.Error().Err(err).Msg("failed update about us content")
		return err
	}

	return nil
}

// DELETE (hard delete, optional)
func (r *aboutUsContentRepository) Delete(id uint) error {
	err := r.DB.DB.Delete(&entity.AboutUsContent{}, id).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed delete about us content")
		return err
	}

	return nil
}