package newsrepository

import (
	"fmt"
	newsdomain "legalgo-BE-go/internal/domain/news"

	"gorm.io/gorm/clause"
)

func (a *accessor) Update(spec newsdomain.News) error {
	tx := a.db.Begin()
	if err := tx.Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns([]string{
			"title",
			"content",
			"featured_image",
			"is_premium",
			"slug",
			"author_id",
			"live_at",
			"updated_at",
		}),
	}).Select(
		"title",
		"content",
		"featured_image",
		"is_premium",
		"slug",
		"author_id",
		"live_at",
		"updated_at",
	).Save(&spec).Error; err != nil {
		tx.Rollback()
		return fmt.Errorf("failed to update news: %v", err)
	}
	if len(spec.Tags) < 1 {
		if err := tx.Model(&spec).Association("Tags").Clear(); err != nil {
			tx.Rollback()
			return fmt.Errorf("failed to clear tags: %v", err)
		}
	}

	if len(spec.Categories) < 1 {
		if err := tx.Model(&spec).Association("Categories").Clear(); err != nil {
			tx.Rollback()
			return fmt.Errorf("failed to clear categories: %v", err)
		}
	}

	if err := tx.Model(&spec).Association("Tags").Append(spec.Tags); err != nil {
		tx.Rollback()
		return fmt.Errorf("failed to add tags: %v", err)
	}

	if err := tx.Model(&spec).Association("Categories").Append(spec.Categories); err != nil {
		tx.Rollback()
		return fmt.Errorf("failed to add categories: %v", err)
	}

	if err := tx.Commit().Error; err != nil {
		return fmt.Errorf("failed to commit transaction: %v", err)
	}

	return nil
}
