package repository

import (
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"

	"github.com/google/uuid"
	"github.com/rs/zerolog"
)

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

type PartnerContentRepository interface {
	Get() ([]entity.PartnerContent, error)
	Create(data *entity.PartnerContent) (*entity.PartnerContent, error)
	Update(id uuid.UUID, data *entity.PartnerContent) error
	UpdateImageFields(id uuid.UUID, imagePath, imageURL string) error
	Delete(id uuid.UUID) error
	FindByID(id uuid.UUID) (*entity.PartnerContent, error) // opsional (buat soft delete)
}

func NewPartnerContentRepository(db *database.Database, logger zerolog.Logger) PartnerContentRepository {
	return &partnerContentRepository{
		DB:  db,
		Log: logger,
	}
}

func (r *partnerContentRepository) Get() ([]entity.PartnerContent, error) {
	var data []entity.PartnerContent

	err := r.DB.DB.
		Find(&data).Error

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

	return data, nil
}

func (r *partnerContentRepository) Create(data *entity.PartnerContent) (*entity.PartnerContent, error) {
	data.ID = uuid.New()

	err := r.DB.DB.Create(data).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed create partner content")
		return nil, err
	}

	return data, nil
}

func (r *partnerContentRepository) Update(id uuid.UUID, data *entity.PartnerContent) error {
	err := r.DB.DB.
		Model(&entity.PartnerContent{}).
		Where("id = ?", id).
		Updates(data).Error

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

	return nil
}

func (r *partnerContentRepository) UpdateImageFields(id uuid.UUID, imagePath, imageURL string) error {
	err := r.DB.DB.
		Model(&entity.PartnerContent{}).
		Where("id = ?", id).
		Updates(map[string]interface{}{
			"image_path": imagePath,
			"image_url":  imageURL,
		}).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed update partner logo")
		return err
	}
	return nil
}

func (r *partnerContentRepository) Delete(id uuid.UUID) error {
	err := r.DB.DB.Delete(&entity.PartnerContent{}, id).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed delete partner content")
		return err
	}

	return nil
}

func (r *partnerContentRepository) FindByID(id uuid.UUID) (*entity.PartnerContent, error) {
	var data entity.PartnerContent

	err := r.DB.DB.
		First(&data, "id = ?", id).Error

	if err != nil {
		r.Log.Error().Err(err).Msg("failed find partner content by id")
		return nil, err
	}

	return &data, nil
}