package controllers

import (
	"os"

	"github.com/gofiber/fiber/v2"
	"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
)

// StatusPage sirve la página pública /status que consulta la API de Atlassian Statuspage.
// Configura la variable de entorno STATUSPAGE_PAGE_ID con el ID de tu página
// (ej. "yh6f0r4529hb", visible en https://<id>.statuspage.io).
func StatusPage(c *fiber.Ctx) error {
	pageID := os.Getenv("STATUSPAGE_PAGE_ID")

	data := fiber.Map{
		"title":  "Estado del sistema | ",
		"pageID": pageID,
	}

	if pageID == "" {
		data["error"] = "STATUSPAGE_PAGE_ID no configurado"
		return c.Render("statuspage", data, "layouts/landing")
	}

	summary, err := models.FetchStatuspageSummary(pageID)
	if err != nil {
		data["error"] = "No se pudo obtener el estado en este momento. Intenta de nuevo más tarde."
		return c.Render("statuspage", data, "layouts/landing")
	}

	// Separar componentes de grupos y componentes normales
	var groups []models.StatuspageComponent
	var components []models.StatuspageComponent
	for _, comp := range summary.Components {
		if comp.Group {
			groups = append(groups, comp)
		} else {
			components = append(components, comp)
		}
	}

	// Helpers de presentación
	type CompVM struct {
		models.StatuspageComponent
		StatusLabel string
		StatusColor string
	}
	toVM := func(comps []models.StatuspageComponent) []CompVM {
		out := make([]CompVM, 0, len(comps))
		for _, c := range comps {
			color := "green"
			switch c.Status {
			case "degraded_performance":
				color = "yellow"
			case "partial_outage":
				color = "orange"
			case "major_outage":
				color = "red"
			case "under_maintenance":
				color = "blue"
			}
			out = append(out, CompVM{
				StatuspageComponent: c,
				StatusLabel:         models.ComponentStatusLabel(c.Status),
				StatusColor:         color,
			})
		}
		return out
	}

	data["summary"] = summary
	data["components"] = toVM(components)
	data["groups"] = toVM(groups)
	data["indicatorColor"] = models.IndicatorColor(summary.Status.Indicator)
	data["hasIncidents"] = len(summary.Incidents) > 0
	data["hasMaintenance"] = len(summary.ScheduledMaintenances) > 0

	return c.Render("statuspage", data, "layouts/landing")
}
