package mysql

import (
	"context"
	"errors"
	"strings"

	"gorm.io/gorm"

	filemanager "wucher/internal/domain/file_manager"
)

type FileManagerAttachmentRepository struct {
	db *gorm.DB
}

func NewFileManagerAttachmentRepository(db *gorm.DB) *FileManagerAttachmentRepository {
	return &FileManagerAttachmentRepository{db: db}
}

func (r *FileManagerAttachmentRepository) Create(ctx context.Context, row *filemanager.Attachment) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *FileManagerAttachmentRepository) Delete(ctx context.Context, id []byte) error {
	res := r.db.WithContext(ctx).Where("id = ?", id).Delete(&filemanager.Attachment{})
	if res.Error != nil {
		return res.Error
	}
	if res.RowsAffected == 0 {
		return gorm.ErrRecordNotFound
	}
	return nil
}

func (r *FileManagerAttachmentRepository) GetByID(ctx context.Context, id []byte) (*filemanager.Attachment, error) {
	var row filemanager.Attachment
	err := r.db.WithContext(ctx).
		Preload("File").
		Where("id = ?", id).
		First(&row).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &row, err
}

func (r *FileManagerAttachmentRepository) GetByRefAndFile(ctx context.Context, refType, refID string, fileID []byte) (*filemanager.Attachment, error) {
	refType = strings.ToLower(strings.TrimSpace(refType))
	refID = strings.TrimSpace(refID)
	if refType == "" || refID == "" || len(fileID) == 0 {
		return nil, nil
	}

	var row filemanager.Attachment
	err := r.db.WithContext(ctx).
		Where("ref_type = ? AND ref_id = ? AND file_id = ?", refType, refID, fileID).
		First(&row).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &row, err
}

func (r *FileManagerAttachmentRepository) ListByReference(ctx context.Context, filter filemanager.AttachmentListFilter) ([]filemanager.Attachment, int64, error) {
	refType := strings.ToLower(strings.TrimSpace(filter.RefType))
	refID := strings.TrimSpace(filter.RefID)
	if refType == "" || refID == "" {
		return []filemanager.Attachment{}, 0, nil
	}

	var rows []filemanager.Attachment
	var total int64

	base := r.db.WithContext(ctx).
		Model(&filemanager.Attachment{}).
		Preload("File").
		Where("ref_type = ? AND ref_id = ?", refType, refID)

	if filter.Category != nil {
		category := strings.TrimSpace(*filter.Category)
		if category == "" {
			base = base.Where("category IS NULL")
		} else {
			base = base.Where("category = ?", category)
		}
	}

	query := base
	if strings.TrimSpace(filter.Sort) != "" {
		query = query.Order(filter.Sort)
	}
	if err := base.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	if filter.Limit > 0 {
		query = query.Limit(filter.Limit).Offset(filter.Offset)
	}
	if err := query.Find(&rows).Error; err != nil {
		return nil, 0, err
	}

	return rows, total, nil
}
