package media

import (
	"context"
	"fmt"
	"math"
	"net/http"
	"os"
	"strconv"

	"fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
	"fr.latosa-escrima/utils"
)

func HandleMedia(w http.ResponseWriter, r *http.Request) {
	queryParams := r.URL.Query()
	page, err := strconv.Atoi(queryParams.Get("page"))
	limit, err := strconv.Atoi(queryParams.Get("limit"))
	if page < 0 {
		page = 0
	}
	if limit <= 0 {
		limit = 10
	}
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}

	offset := (page - 1) * limit

	total, err := core.DB.NewSelect().
		Model((*models.Media)(nil)).
		Count(context.Background())

	upperBound := float64(total) / float64(limit)
	totalPages := int(math.Max(1, math.Ceil(upperBound)))

	var media []models.Media
	err = core.DB.NewSelect().
		Model(&media).
		Limit(limit).
		Offset(offset).
		Scan(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}
	scheme := "http"
	if r.TLS != nil || os.Getenv("ENVIRONMENT") != "DEV" { // Check if the request is over HTTPS
		scheme = "https"
	}

	// Extract the host
	host := r.Host
	baseURL := fmt.Sprintf("%s://%s", scheme, host)
	if os.Getenv("ENVIRONMENT") != "DEV" {
		baseURL += "/api"
	}
	media = utils.Map(media, func(m models.Media) models.Media {
		m.Author = nil
		m.URL = fmt.Sprintf("%s/media/%s/file", baseURL, m.ID)
		return m
	})

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Media successfully retrieved",
		Data: core.Paginated[models.Media]{
			Page:       page,
			Limit:      limit,
			TotalPages: totalPages,
			Items:      media,
		},
	}.Respond(w, http.StatusOK)
}

func HandleMediaDetails(w http.ResponseWriter, r *http.Request) {
	uuid := r.PathValue("media_uuid")
	var media models.Media
	err := core.DB.NewSelect().
		Model(&media).
		Where("id = ?", uuid).
		Limit(1).
		Scan(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	baseURL := utils.GetURL(r)
	media.URL = fmt.Sprintf("%s/file", baseURL)

	media.Author = nil
	core.JSONSuccess{
		Status:  core.Success,
		Message: "Media retrieved",
		Data:    media,
	}.Respond(w, http.StatusOK)
}

func HandleMediaFile(w http.ResponseWriter, r *http.Request) {
	uuid := r.PathValue("media_uuid")
	var media models.Media
	err := core.DB.NewSelect().
		Model(&media).
		Where("id = ?", uuid).
		Limit(1).
		Scan(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	http.ServeFile(w, r, media.Path)

}
