package service

import (
	"context"
	"github.com/gofiber/fiber/v2"
	"github.com/google/uuid"
	"github.com/minio/minio-go/v7"
	"github.com/rs/zerolog"
	"io"
	"log"
	"math/rand"
	"mime"
	"netidhub-saas-be/app/database/entity"
	"netidhub-saas-be/app/module/article_categories/mapper"
	"netidhub-saas-be/app/module/article_categories/repository"
	"netidhub-saas-be/app/module/article_categories/request"
	"netidhub-saas-be/app/module/article_categories/response"
	usersRepository "netidhub-saas-be/app/module/users/repository"
	config "netidhub-saas-be/config/config"
	minioStorage "netidhub-saas-be/config/config"
	"netidhub-saas-be/utils/paginator"
	utilSvc "netidhub-saas-be/utils/service"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// ArticleCategoriesService
type articleCategoriesService struct {
	Repo         repository.ArticleCategoriesRepository
	UsersRepo    usersRepository.UsersRepository
	MinioStorage *minioStorage.MinioStorage
	Log          zerolog.Logger
	Cfg          *config.Config
}

// ArticleCategoriesService define interface of IArticleCategoriesService
type ArticleCategoriesService interface {
	All(authToken string, req request.ArticleCategoriesQueryRequest) (articleCategories []*response.ArticleCategoriesResponse, paging paginator.Pagination, err error)
	Show(authToken string, id uint) (articleCategories *response.ArticleCategoriesResponse, err error)
	ShowByOldId(authToken string, id uint) (articleCategories *response.ArticleCategoriesResponse, err error)
	ShowBySlug(authToken string, slug string) (articleCategories *response.ArticleCategoriesResponse, err error)
	Save(authToken string, req request.ArticleCategoriesCreateRequest) (articleCategories *entity.ArticleCategories, err error)
	SaveThumbnail(authToken string, c *fiber.Ctx) (err error)
	Update(authToken string, id uint, req request.ArticleCategoriesUpdateRequest) (err error)
	Delete(authToken string, id uint) error
	Viewer(c *fiber.Ctx) error
}

// NewArticleCategoriesService init ArticleCategoriesService
func NewArticleCategoriesService(repo repository.ArticleCategoriesRepository, usersRepo usersRepository.UsersRepository, minioStorage *minioStorage.MinioStorage, log zerolog.Logger, cfg *config.Config) ArticleCategoriesService {

	return &articleCategoriesService{
		Repo:         repo,
		UsersRepo:    usersRepo,
		MinioStorage: minioStorage,
		Log:          log,
		Cfg:          cfg,
	}
}

// All implement interface of ArticleCategoriesService
func (_i *articleCategoriesService) All(authToken string, req request.ArticleCategoriesQueryRequest) (articleCategoriess []*response.ArticleCategoriesResponse, paging paginator.Pagination, err error) {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	// createdBy := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
	// if createdBy != nil {
	// 	if createdBy.UserLevel.LevelNumber > 1 {
	// 		req.UserLevelId = &createdBy.UserLevelId
	// 	}
	// }

	results, paging, err := _i.Repo.GetAll(clientId, req)
	if err != nil {
		return
	}

	host := _i.Cfg.App.Domain
	for _, result := range results {
		articleCategoriess = append(articleCategoriess, mapper.ArticleCategoriesResponseMapper(result, host))
	}

	return
}

func (_i *articleCategoriesService) Show(authToken string, id uint) (articleCategories *response.ArticleCategoriesResponse, err error) {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	result, err := _i.Repo.FindOne(clientId, id)
	if err != nil {
		return nil, err
	}
	host := _i.Cfg.App.Domain
	return mapper.ArticleCategoriesResponseMapper(result, host), nil
}

func (_i *articleCategoriesService) ShowByOldId(authToken string, id uint) (articleCategories *response.ArticleCategoriesResponse, err error) {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	result, err := _i.Repo.FindOneByOldId(clientId, id)
	if err != nil {
		return nil, err
	}
	host := _i.Cfg.App.Domain
	return mapper.ArticleCategoriesResponseMapper(result, host), nil
}

func (_i *articleCategoriesService) ShowBySlug(authToken string, slug string) (articleCategories *response.ArticleCategoriesResponse, err error) {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	result, err := _i.Repo.FindOneBySlug(clientId, slug)
	if err != nil {
		return nil, err
	}
	host := _i.Cfg.App.Domain
	return mapper.ArticleCategoriesResponseMapper(result, host), nil
}

func (_i *articleCategoriesService) Save(authToken string, req request.ArticleCategoriesCreateRequest) (articleCategories *entity.ArticleCategories, err error) {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	_i.Log.Info().Interface("data", req).Msg("")
	newReq := req.ToEntity()

	if clientId != nil {
		newReq.ClientId = clientId
	}

	if req.CreatedById != nil {
		createdBy, err := _i.UsersRepo.FindOne(clientId, *req.CreatedById)
		if err != nil {
			return nil, err
		}
		newReq.CreatedById = &createdBy.ID
	} else {
		createdBy := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		newReq.CreatedById = &createdBy.ID
	}

	return _i.Repo.Create(newReq)
}

func (_i *articleCategoriesService) SaveThumbnail(authToken string, c *fiber.Ctx) (err error) {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	bucketName := _i.MinioStorage.Cfg.ObjectStorage.MinioStorage.BucketName

	form, err := c.MultipartForm()
	if err != nil {
		return err
	}
	files := form.File["files"]

	// Create minio connection.
	minioClient, err := _i.MinioStorage.ConnectMinio()
	if err != nil {
		// Return status 500 and minio connection error.
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": true,
			"msg":   err.Error(),
		})
	}

	// Iterasi semua file yang diunggah
	for _, file := range files {
		_i.Log.Info().Str("timestamp", time.Now().
			Format(time.RFC3339)).Str("Service:Resource", "Uploader:: loop1").
			Interface("data", file).Msg("")

		src, err := file.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		filename := filepath.Base(file.Filename)
		filenameWithoutExt := filepath.Clean(filename[:len(filename)-len(filepath.Ext(filename))])
		extension := filepath.Ext(file.Filename)[1:]

		rand.New(rand.NewSource(time.Now().UnixNano()))
		randUniqueId := rand.Intn(1000000)

		newFilenameWithoutExt := filenameWithoutExt + "_" + strconv.Itoa(randUniqueId)
		newFilename := newFilenameWithoutExt + "." + extension
		objectName := "articles/category/thumbnail/" + newFilename

		findCategory, err := _i.Repo.FindOne(clientId, uint(id))
		findCategory.ThumbnailPath = &objectName
		err = _i.Repo.Update(clientId, uint(id), findCategory)
		if err != nil {
			return err
		}

		// Upload file ke MinIO
		_, err = minioClient.PutObject(context.Background(), bucketName, objectName, src, file.Size, minio.PutObjectOptions{})
		if err != nil {
			return err
		}
	}

	return
}

func (_i *articleCategoriesService) Update(authToken string, id uint, req request.ArticleCategoriesUpdateRequest) (err error) {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	_i.Log.Info().Interface("data", req).Msg("")

	newReq := req.ToEntity()
	if clientId != nil {
		newReq.ClientId = clientId
	}
	if req.CreatedById != nil {
		createdBy, err := _i.UsersRepo.FindOne(clientId, *req.CreatedById)
		if err != nil {
			return err
		}
		newReq.CreatedById = &createdBy.ID
	}

	return _i.Repo.Update(clientId, id, newReq)
}

func (_i *articleCategoriesService) Delete(authToken string, id uint) error {
	// Extract clientId from authToken
	var clientId *uuid.UUID
	if authToken != "" {
		user := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
		if user != nil && user.ClientId != nil {
			clientId = user.ClientId
			_i.Log.Info().Interface("clientId", clientId).Msg("Extracted clientId from auth token")
		}
	}

	result, err := _i.Repo.FindOne(clientId, id)
	if err != nil {
		return err
	}

	isActive := false
	result.IsActive = &isActive
	if clientId != nil {
		result.ClientId = clientId
	}
	return _i.Repo.Update(clientId, id, result)
}

func (_i *articleCategoriesService) Viewer(c *fiber.Ctx) (err error) {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	result, err := _i.Repo.FindOne(nil, uint(id))
	if err != nil {
		return err
	}

	if result.ThumbnailPath == nil {
		return nil
	}

	ctx := context.Background()
	bucketName := _i.MinioStorage.Cfg.ObjectStorage.MinioStorage.BucketName
	objectName := result.ThumbnailPath

	_i.Log.Info().Str("timestamp", time.Now().
		Format(time.RFC3339)).Str("Service:Resource", "Article:Uploads").
		Interface("data", objectName).Msg("")

	// Create minio connection.
	minioClient, err := _i.MinioStorage.ConnectMinio()
	if err != nil {
		// Return status 500 and minio connection error.
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": true,
			"msg":   err.Error(),
		})
	}

	fileContent, err := minioClient.GetObject(ctx, bucketName, *objectName, minio.GetObjectOptions{})
	if err != nil {
		log.Fatalln(err)
	}
	defer fileContent.Close()

	contentType := mime.TypeByExtension("." + getFileExtension(*objectName))
	if contentType == "" {
		contentType = "application/octet-stream"
	}

	c.Set("Content-Type", contentType)

	if _, err := io.Copy(c.Response().BodyWriter(), fileContent); err != nil {
		return err
	}

	return
}

func getFileExtension(filename string) string {
	// split file name
	parts := strings.Split(filename, ".")

	// jika tidak ada ekstensi, kembalikan string kosong
	if len(parts) == 1 || (len(parts) == 2 && parts[0] == "") {
		return ""
	}

	// ambil ekstensi terakhir
	return parts[len(parts)-1]
}
