package repositories

import (
	"log"
	"time"

	"github.com/niangaodev/art-code/config"
	"github.com/niangaodev/art-code/models"
	"gorm.io/gorm"
)

// GetTags 获取所有标签
func GetTags() ([]models.Tag, error) {
	var tags []models.Tag
	err := config.DB.Model(&models.Tag{}).
		Where("deleted_at = ?", 0).
		Order("name ASC").
		Find(&tags).Error
	if err != nil {
		log.Printf("Error querying tags: %v", err)
		return nil, err
	}
	return tags, nil
}

// GetTagByID 根据ID获取标签
func GetTagByID(id uint) (*models.Tag, error) {
	var tag models.Tag
	err := config.DB.Model(&models.Tag{}).
		Where("id = ? AND deleted_at = ?", id, 0).
		First(&tag).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting tag by ID: %v", err)
		return nil, err
	}
	return &tag, nil
}

// GetTagBySlug 根据Slug获取标签
func GetTagBySlug(slug string) (*models.Tag, error) {
	var tag models.Tag
	err := config.DB.Model(&models.Tag{}).
		Where("slug = ? AND deleted_at = ?", slug, 0).
		First(&tag).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting tag by slug: %v", err)
		return nil, err
	}
	return &tag, nil
}

// CreateTag 创建标签
func CreateTag(tag *models.Tag) error {
	err := config.DB.Create(tag).Error
	if err != nil {
		log.Printf("Error creating tag: %v", err)
		return err
	}
	return nil
}

// UpdateTag 更新标签
func UpdateTag(tag *models.Tag) error {
	err := config.DB.Model(&models.Tag{}).
		Where("id = ? AND deleted_at = ?", tag.ID, 0).
		Updates(map[string]interface{}{
			"name":       tag.Name,
			"slug":       tag.Slug,
			"updated_at": time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating tag: %v", err)
		return err
	}
	return nil
}

// DeleteTag 删除标签 (Soft Delete)
func DeleteTag(id uint) error {
	// 软删除标签
	err := config.DB.Model(&models.Tag{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting tag: %v", err)
		return err
	}

	// 物理删除关联关系
	err = config.DB.Where("tag_id = ?", id).Delete(&models.PostTag{}).Error
	if err != nil {
		log.Printf("Error deleting post-tag relationships: %v", err)
		return err
	}

	return nil
}

// GetTagsByPostID 根据文章ID获取标签
func GetTagsByPostID(postID uint) ([]models.Tag, error) {
	var tags []models.Tag
	err := config.DB.Model(&models.Tag{}).
		Joins("JOIN post_tags pt ON tags.id = pt.tag_id").
		Where("pt.post_id = ? AND tags.deleted_at = ?", postID, 0).
		Order("tags.name ASC").
		Find(&tags).Error
	if err != nil {
		log.Printf("Error querying tags by post ID: %v", err)
		return nil, err
	}
	return tags, nil
}

// AddTagToPost 为文章添加标签
func AddTagToPost(postID uint, tagID uint) error {
	postTag := &models.PostTag{
		PostID:    postID,
		TagID:     tagID,
		CreatedAt: time.Now().Unix(),
	}
	err := config.DB.Where("post_id = ? AND tag_id = ?", postID, tagID).
		FirstOrCreate(postTag).Error
	if err != nil {
		log.Printf("Error adding tag to post: %v", err)
		return err
	}
	return nil
}

// RemoveTagFromPost 从文章移除标签
func RemoveTagFromPost(postID uint, tagID uint) error {
	err := config.DB.Where("post_id = ? AND tag_id = ?", postID, tagID).
		Delete(&models.PostTag{}).Error
	if err != nil {
		log.Printf("Error removing tag from post: %v", err)
		return err
	}
	return nil
}

// GetPostsByTagID 根据标签ID获取文章
func GetPostsByTagID(tagID uint) ([]models.Post, error) {
	var posts []models.Post
	err := config.DB.Model(&models.Post{}).
		Joins("JOIN post_tags pt ON posts.id = pt.post_id").
		Where("pt.tag_id = ? AND posts.is_published = ? AND posts.deleted_at = ?", tagID, 1, 0).
		Order("posts.created_at DESC").
		Find(&posts).Error
	if err != nil {
		log.Printf("Error querying posts by tag ID: %v", err)
		return nil, err
	}
	return posts, nil
}

// BuildTagsResponse 构建标签列表响应
func BuildTagsResponse(tags []models.Tag) []models.TagResponse {
	responses := make([]models.TagResponse, 0, len(tags))
	for _, tag := range tags {
		responses = append(responses, *BuildTagResponse(&tag))
	}
	return responses
}

// BuildTagResponse 构建标签响应
func BuildTagResponse(tag *models.Tag) *models.TagResponse {
	return &models.TagResponse{
		ID:        tag.ID,
		Name:      tag.Name,
		Slug:      tag.Slug,
		CreatedAt: formatTimestamp(tag.CreatedAt),
		UpdatedAt: formatTimestamp(tag.UpdatedAt),
	}
}
