package repository

import (
	"fmt"
	"strings"
	"time"
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/article_files/request"
	"web-qudo-be/utils/paginator"
	utilSvc "web-qudo-be/utils/service"

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

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

// ArticleFilesRepository define interface of IArticleFilesRepository
type ArticleFilesRepository interface {
	GetAll(clientId *uuid.UUID, req request.ArticleFilesQueryRequest) (articleFiless []*entity.ArticleFiles, paging paginator.Pagination, err error)
	FindOne(clientId *uuid.UUID, id uint) (articleFiles *entity.ArticleFiles, err error)
	FindByArticle(clientId *uuid.UUID, articleId uint) (articleFiles []*entity.ArticleFiles, err error)
	FindByFilename(clientId *uuid.UUID, filename string) (articleFiles *entity.ArticleFiles, err error)
	Create(clientId *uuid.UUID, articleFiles *entity.ArticleFiles) (err error)
	Update(clientId *uuid.UUID, id uint, articleFiles *entity.ArticleFiles) (err error)
	Delete(clientId *uuid.UUID, id uint) (err error)
}

func NewArticleFilesRepository(db *database.Database, log zerolog.Logger) ArticleFilesRepository {
	return &articleFilesRepository{
		DB:  db,
		Log: log,
	}
}

// implement interface of IArticleFilesRepository
func (_i *articleFilesRepository) GetAll(clientId *uuid.UUID, req request.ArticleFilesQueryRequest) (articleFiless []*entity.ArticleFiles, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.ArticleFiles{})
	query = query.Where("is_active = ?", true)

	// Add client filter
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}

	if req.ArticleId != nil {
		query = query.Where("article_id = ?", req.ArticleId)
	}
	if req.FileName != nil && *req.FileName != "" {
		fileName := strings.ToLower(*req.FileName)
		query = query.Where("LOWER(file_name) LIKE ?", "%"+strings.ToLower(fileName)+"%")
	}
	if req.IsPublish != nil {
		query = query.Where("is_publish = ?", req.IsPublish)
	}
	if req.StatusId != nil {
		query = query.Where("status_id = ?", req.StatusId)
	}
	query.Count(&count)

	if req.Pagination.SortBy != "" {
		direction := "ASC"
		if req.Pagination.Sort == "desc" {
			direction = "DESC"
		}
		query.Order(fmt.Sprintf("%s %s", req.Pagination.SortBy, direction))
	}

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&articleFiless).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *articleFilesRepository) FindOne(clientId *uuid.UUID, id uint) (articleFiles *entity.ArticleFiles, err error) {
	query := _i.DB.DB
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	if err := query.First(&articleFiles, id).Error; err != nil {
		return nil, err
	}

	return articleFiles, nil
}

func (_i *articleFilesRepository) FindByArticle(clientId *uuid.UUID, articleId uint) (articleFiles []*entity.ArticleFiles, err error) {
	query := _i.DB.DB.Where("article_id = ?", articleId)
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	if err := query.Find(&articleFiles).Error; err != nil {
		return nil, err
	}

	return articleFiles, nil
}

func (_i *articleFilesRepository) FindByFilename(clientId *uuid.UUID, articleFilename string) (articleFiles *entity.ArticleFiles, err error) {
	query := _i.DB.DB.Where("file_name = ?", articleFilename)
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	if err := query.First(&articleFiles).Error; err != nil {
		return nil, err
	}

	return articleFiles, nil
}

func (_i *articleFilesRepository) Create(clientId *uuid.UUID, articleFiles *entity.ArticleFiles) (err error) {
	// Set client ID
	if clientId != nil {
		articleFiles.ClientId = clientId
	}
	return _i.DB.DB.Create(articleFiles).Error
}

func (_i *articleFilesRepository) Update(clientId *uuid.UUID, id uint, articleFiles *entity.ArticleFiles) (err error) {
	// Validate client access
	if clientId != nil {
		var count int64
		if err := _i.DB.DB.Model(&entity.ArticleFiles{}).Where("id = ? AND client_id = ?", id, clientId).Count(&count).Error; err != nil {
			return err
		}
		if count == 0 {
			return fmt.Errorf("access denied to this resource")
		}
	}

	// Create a copy without the relation field to avoid updating non-existent columns
	updateData := &entity.ArticleFiles{
		ID:            articleFiles.ID,
		ArticleId:     articleFiles.ArticleId,
		UploadID:      articleFiles.UploadID,
		FilePath:      articleFiles.FilePath,
		FileUrl:       articleFiles.FileUrl,
		FileName:      articleFiles.FileName,
		FileThumbnail: articleFiles.FileThumbnail,
		FileAlt:       articleFiles.FileAlt,
		WidthPixel:    articleFiles.WidthPixel,
		HeightPixel:   articleFiles.HeightPixel,
		Size:          articleFiles.Size,
		DownloadCount: articleFiles.DownloadCount,
		CreatedById:   articleFiles.CreatedById,
		StatusId:      articleFiles.StatusId,
		IsPublish:     articleFiles.IsPublish,
		PublishedAt:   articleFiles.PublishedAt,
		ClientId:      articleFiles.ClientId,
		IsActive:      articleFiles.IsActive,
		CreatedAt:     articleFiles.CreatedAt,
		UpdatedAt:     time.Time{},
		// Exclude Article relation field
	}

	articleFilesMap, err := utilSvc.StructToMap(updateData)
	if err != nil {
		return err
	}

	// Remove any relation fields that might have been included
	delete(articleFilesMap, "article")

	_i.Log.Info().Interface("articleFilesMap : ", articleFilesMap).Msg("")

	return _i.DB.DB.Model(&entity.ArticleFiles{}).
		Where(&entity.ArticleFiles{ID: id}).
		Updates(articleFilesMap).Error
}

func (_i *articleFilesRepository) Delete(clientId *uuid.UUID, id uint) error {
	// Validate client access
	if clientId != nil {
		var count int64
		if err := _i.DB.DB.Model(&entity.ArticleFiles{}).Where("id = ? AND client_id = ?", id, clientId).Count(&count).Error; err != nil {
			return err
		}
		if count == 0 {
			return fmt.Errorf("access denied to this resource")
		}
	}

	return _i.DB.DB.Delete(&entity.ArticleFiles{}, id).Error
}
