package service

import (
	"context"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"github.com/minio/minio-go/v7"
	"github.com/rs/zerolog"
	"io"
	"log"
	"math/rand"
	"mime"
	"netidhub-saas-be/app/module/magazine_files/mapper"
	"netidhub-saas-be/app/module/magazine_files/repository"
	"netidhub-saas-be/app/module/magazine_files/request"
	"netidhub-saas-be/app/module/magazine_files/response"
	config "netidhub-saas-be/config/config"
	minioStorage "netidhub-saas-be/config/config"
	"netidhub-saas-be/utils/paginator"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// MagazineFilesService
type magazineFilesService struct {
	Repo         repository.MagazineFilesRepository
	Log          zerolog.Logger
	Cfg          *config.Config
	MinioStorage *minioStorage.MinioStorage
}

// MagazineFilesService define interface of IMagazineFilesService
type MagazineFilesService interface {
	All(req request.MagazineFilesQueryRequest) (magazineFiles []*response.MagazineFilesResponse, paging paginator.Pagination, err error)
	Show(id uint) (magazineFiles *response.MagazineFilesResponse, err error)
	Save(c *fiber.Ctx, id uint, title string, description string) (err error)
	Update(id uint, req request.MagazineFilesUpdateRequest) (err error)
	Delete(id uint) error
	Viewer(c *fiber.Ctx) error
}

// NewMagazineFilesService init MagazineFilesService
func NewMagazineFilesService(repo repository.MagazineFilesRepository, log zerolog.Logger, cfg *config.Config, minioStorage *minioStorage.MinioStorage) MagazineFilesService {

	return &magazineFilesService{
		Repo:         repo,
		Log:          log,
		Cfg:          cfg,
		MinioStorage: minioStorage,
	}
}

// All implement interface of MagazineFilesService
func (_i *magazineFilesService) All(req request.MagazineFilesQueryRequest) (magazineFiless []*response.MagazineFilesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}
	host := _i.Cfg.App.Domain
	for _, result := range results {
		magazineFiless = append(magazineFiless, mapper.MagazineFilesResponseMapper(result, host))
	}
	return
}

func (_i *magazineFilesService) Show(id uint) (magazineFiles *response.MagazineFilesResponse, err error) {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return nil, err
	}
	host := _i.Cfg.App.Domain
	return mapper.MagazineFilesResponseMapper(result, host), nil
}

func (_i *magazineFilesService) Save(c *fiber.Ctx, id uint, title string, description string) (err error) {
	bucketName := _i.MinioStorage.Cfg.ObjectStorage.MinioStorage.BucketName

	form, err := c.MultipartForm()

	if err != nil {
		return err
	}
	//filess := 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(),
		})
	}

	for _, files := range form.File {

		_i.Log.Info().Str("timestamp", time.Now().
			Format(time.RFC3339)).Str("Service:Resource", "Uploader:: top").
			Interface("files", files).Msg("")

		for _, fileHeader := range files {
			_i.Log.Info().Str("timestamp", time.Now().
				Format(time.RFC3339)).Str("Service:Resource", "Uploader:: loop").
				Interface("data", fileHeader).Msg("")

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

			filename := filepath.Base(fileHeader.Filename)
			filenameAlt := filepath.Clean(filename[:len(filename)-len(filepath.Ext(filename))])
			filename = strings.ReplaceAll(filename, " ", "")
			filenameWithoutExt := filepath.Clean(filename[:len(filename)-len(filepath.Ext(filename))])
			extension := filepath.Ext(fileHeader.Filename)[1:]

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

			newFilenameWithoutExt := filenameWithoutExt + "_" + strconv.Itoa(randUniqueId)
			newFilename := newFilenameWithoutExt + "." + extension
			objectName := fmt.Sprintf("magazines/upload/%d/%d/%s", now.Year(), now.Month(), newFilename)

			fileSize := strconv.FormatInt(fileHeader.Size, 10)

			req := request.MagazineFilesCreateRequest{
				MagazineId:  id,
				Title:       title,
				Description: description,
				FilePath:    &objectName,
				FileName:    &newFilename,
				FileAlt:     &filenameAlt,
				Size:        &fileSize,
			}

			err = _i.Repo.Create(req.ToEntity())
			if err != nil {
				return err
			}

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

	_i.Log.Info().Str("timestamp", time.Now().
		Format(time.RFC3339)).Str("Service:Resource", "User:All").
		Interface("data", "Successfully uploaded").Msg("")

	return
}

func (_i *magazineFilesService) Viewer(c *fiber.Ctx) (err error) {
	filename := c.Params("filename")
	result, err := _i.Repo.FindByFilename(filename)
	if err != nil {
		return err
	}

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

	_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()

	// Tentukan Content-Type berdasarkan ekstensi file
	contentType := mime.TypeByExtension("." + getFileExtension(objectName))
	if contentType == "" {
		contentType = "application/octet-stream" // fallback jika tidak ada tipe MIME yang cocok
	}

	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]
}

func (_i *magazineFilesService) Update(id uint, req request.MagazineFilesUpdateRequest) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")
	return _i.Repo.Update(id, req.ToEntity())
}

func (_i *magazineFilesService) Delete(id uint) error {
	return _i.Repo.Delete(id)
}
