package repository

import (
	"strings"
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/utils/paginator"

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

type MediaLibraryRepository interface {
	FindByPublicURLAny(publicURL string) (*entity.MediaLibraryItem, error)
	Create(item *entity.MediaLibraryItem) error
	Update(id uint, fields map[string]interface{}) error
	GetAll(clientID *uuid.UUID, q string, sourceType *string, p *paginator.Pagination) ([]*entity.MediaLibraryItem, *paginator.Pagination, error)
	SoftDelete(clientID *uuid.UUID, id uint) error
}

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

func NewMediaLibraryRepository(db *database.Database, log zerolog.Logger) MediaLibraryRepository {
	return &mediaLibraryRepository{DB: db, Log: log}
}

func (_i *mediaLibraryRepository) FindByPublicURLAny(publicURL string) (*entity.MediaLibraryItem, error) {
	var row entity.MediaLibraryItem
	err := _i.DB.DB.Where("public_url = ?", publicURL).First(&row).Error
	if err != nil {
		return nil, err
	}
	return &row, nil
}

func (_i *mediaLibraryRepository) Create(item *entity.MediaLibraryItem) error {
	return _i.DB.DB.Create(item).Error
}

func (_i *mediaLibraryRepository) Update(id uint, fields map[string]interface{}) error {
	return _i.DB.DB.Model(&entity.MediaLibraryItem{}).Where("id = ?", id).Updates(fields).Error
}

func (_i *mediaLibraryRepository) GetAll(clientID *uuid.UUID, q string, sourceType *string, p *paginator.Pagination) ([]*entity.MediaLibraryItem, *paginator.Pagination, error) {
	var rows []*entity.MediaLibraryItem
	var count int64

	query := _i.DB.DB.Model(&entity.MediaLibraryItem{}).Where("is_active = ?", true)
	if clientID != nil {
		query = query.Where("client_id = ?", clientID)
	}
	if sourceType != nil && strings.TrimSpace(*sourceType) != "" {
		query = query.Where("source_type = ?", strings.TrimSpace(*sourceType))
	}
	if strings.TrimSpace(q) != "" {
		like := "%" + strings.ToLower(strings.TrimSpace(q)) + "%"
		query = query.Where(
			"LOWER(COALESCE(original_filename,'')) LIKE ? OR LOWER(public_url) LIKE ? OR LOWER(COALESCE(source_label,'')) LIKE ?",
			like, like, like,
		)
	}
	if err := query.Count(&count).Error; err != nil {
		return nil, p, err
	}
	p.Count = count
	p = paginator.Paging(p)
	err := query.Order("created_at DESC").Offset(p.Offset).Limit(p.Limit).Find(&rows).Error
	return rows, p, err
}

func (_i *mediaLibraryRepository) SoftDelete(clientID *uuid.UUID, id uint) error {
	q := _i.DB.DB.Model(&entity.MediaLibraryItem{}).Where("id = ?", id)
	if clientID != nil {
		q = q.Where("client_id = ?", clientID)
	}
	res := q.Update("is_active", false)
	if res.Error != nil {
		return res.Error
	}
	if res.RowsAffected == 0 {
		return gorm.ErrRecordNotFound
	}
	return nil
}
