package repository

import (
	"fmt"
	"github.com/google/uuid"
	"netidhub-saas-be/app/database"
	"netidhub-saas-be/app/database/entity"
	"netidhub-saas-be/app/module/article_files/request"
	"netidhub-saas-be/utils/paginator"
	utilSvc "netidhub-saas-be/utils/service"
	"strings"
)

type articleFilesRepository struct {
	DB *database.Database
}

// 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) ArticleFilesRepository {
	return &articleFilesRepository{
		DB: db,
	}
}

// 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")
		}
	}

	articleFilesMap, err := utilSvc.StructToMap(articleFiles)
	if err != nil {
		return err
	}
	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
}
