// SPDX-License-Identifier: MIT

package pdfexport

import (
	"encoding/json"
	"strings"

	"code.gitea.io/gitea/modules/setting"
)

func configFromSetting() (pdfConfig, userError) {
	cfg := pdfConfig{
		Determinism: strings.ToLower(setting.PDF.Determinism),
		Timestamp:   strings.ToLower(setting.PDF.Timestamp),
		Typography:  strings.ToLower(setting.PDF.Typography),
	}
	cfg.Mermaid.Strategy = strings.ToLower(setting.PDF.Mermaid.Strategy)
	cfg.Mermaid.Caption = setting.PDF.Mermaid.Caption
	cfg.OrphansWidows.Enforce = setting.PDF.OrphansWidowsEnforce
	cfg.Footer.Enabled = setting.PDF.FooterEnabled

	// Defaults if empty/misconfigured.
	if cfg.Determinism == "" {
		cfg.Determinism = "strict"
	}
	if cfg.Timestamp == "" {
		cfg.Timestamp = "commit_time"
	}
	if cfg.Typography == "" {
		cfg.Typography = "professional"
	}
	if cfg.Mermaid.Strategy == "" {
		cfg.Mermaid.Strategy = "balanced"
	}

	if cfg.Determinism != "strict" && cfg.Determinism != "relaxed" {
		return pdfConfig{}, errBadRequest("ERR_PDF_CONFIG_INVALID", "Invalid PDF configuration.")
	}
	if cfg.Timestamp != "commit_time" && cfg.Timestamp != "render_time" {
		return pdfConfig{}, errBadRequest("ERR_PDF_CONFIG_INVALID", "Invalid PDF configuration.")
	}
	if cfg.Typography != "basic" && cfg.Typography != "professional" {
		return pdfConfig{}, errBadRequest("ERR_PDF_CONFIG_INVALID", "Invalid PDF configuration.")
	}
	if cfg.Mermaid.Strategy != "fast" && cfg.Mermaid.Strategy != "balanced" && cfg.Mermaid.Strategy != "prestige" {
		return pdfConfig{}, errBadRequest("ERR_PDF_CONFIG_INVALID", "Invalid PDF configuration.")
	}

	// Strict implies timestamp=commit_time only.
	if cfg.Determinism == "strict" && cfg.Timestamp != "commit_time" {
		return pdfConfig{}, errBadRequest("ERR_PDF_CONFIG_INVALID", "Invalid PDF configuration.")
	}

	return cfg, userError{}
}

func configHash(cfg pdfConfig) (string, error) {
	b, err := json.Marshal(cfg)
	if err != nil {
		return "", err
	}
	return sha256Hex(b), nil
}

