package backend

import (
	"encoding/json"
	"errors"

	"github.com/jmoiron/sqlx/types"
)

var maxVodsInPlaylist = 50

var ErrInvalidPlaylistJSON = errors.New("backend: invalid playlist json syntax")
var ErrMaxPlaylistSizeReached = errors.New("backend: playlists can have at most 50 videos")
var ErrPlaylistIsEmpty = errors.New("backend: cannot enable a channel with an empty active playlist")

type VodIds struct {
	VodIds []int `json:"vod_ids"`
}

func validatePlaylistJson(playlist types.JsonText) error {
	var vodIds VodIds
	err := json.Unmarshal(playlist, &vodIds)
	if err != nil {
		return ErrInvalidPlaylistJSON
	}
	if len(vodIds.VodIds) > maxVodsInPlaylist {
		return ErrMaxPlaylistSizeReached
	}
	return nil
}

func channelCanBeEnabled(channelID int) error {
	activePlaylist := Playlist{}
	err := db.Get(&activePlaylist, "SELECT playlists.* FROM channels JOIN playlists ON channels.id = playlists.channel_id AND channels.active_playlist_id = playlists.id WHERE channels.id = $1", channelID)
	if err != nil {
		return err
	}
	var vodIds VodIds
	err = json.Unmarshal(activePlaylist.Playlist, &vodIds)
	if err != nil {
		return ErrInvalidPlaylistJSON
	}
	if len(vodIds.VodIds) == 0 {
		return ErrPlaylistIsEmpty
	}
	return nil
}
