package scenarios_service

import (
	"encoding/json"
	"evening_detective_server/internal/modules/storytelling"
	"evening_detective_server/internal/repos"
)

func mapScenariosLight(
	o []*repos.Scenario,
	domain string,
) []*Scenario {
	res := make([]*Scenario, 0, len(o))
	for _, item := range o {
		res = append(res, MapScenarioLight(item, domain))
	}
	return res
}

func mapScenarios(
	o []*repos.Scenario,
	domain string,
) ([]*Scenario, error) {
	res := make([]*Scenario, 0, len(o))
	for _, item := range o {
		scenario, err := mapScenario(item, domain)
		if err != nil {
			return nil, err
		}
		res = append(res, scenario)
	}
	return res, nil
}

func MapScenarioLight(
	o *repos.Scenario,
	domain string,
) *Scenario {
	if o == nil {
		return nil
	}
	return &Scenario{
		ID:          o.ID,
		Name:        o.Name,
		Description: o.Description,
		Image:       mapImage(o.Image, domain),
		Story:       nil,
		Author:      o.Author,
		Status:      o.Status,
		UpdatedAt:   o.UpdatedAt,
		CreatedAt:   o.CreatedAt,
		PublishedAt: o.PublishedAt,
		IsDeleted:   o.IsDeleted,
	}
}

func mapScenario(
	o *repos.Scenario,
	domain string,
) (*Scenario, error) {
	scenario := MapScenarioLight(o, domain)
	story, err := mapStory(o.Scenario, domain)
	if err != nil {
		return nil, err
	}
	scenario.Story = story
	return scenario, nil
}

func mapStory(o string, domain string) (*storytelling.Story, error) {
	res := &storytelling.Story{}
	if err := json.Unmarshal([]byte(o), res); err != nil {
		return nil, err
	}
	for _, place := range res.Places {
		if place.Image != "" {
			place.Image = domain + place.Image
		}
	}
	return res, nil
}

func convertStory(o *storytelling.Story) (string, error) {
	b, err := json.Marshal(o)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

func mapImage(image *string, domain string) *string {
	if image == nil || *image == "" {
		u := domain + "question.png"
		return &u
	}
	u := domain + *image
	return &u
}
