package handlers

// Submission base catalog handler — Composer Slice A (t-paliad-313,
// m/paliad#141, design doc docs/design-submission-generator-v2-2026-05-26.md
// §5.1 / Slice A acceptance).
//
// Endpoint: GET /api/submission-bases  → list of active bases visible
// to the requesting firm. The sidebar picker on the draft editor reads
// this once on page load and caches in-memory; the response shape is
// stable across the picker's lifetime.
//
// Visibility: the catalog is shared firm-wide (per the design + mig
// 146's wide-open RLS SELECT policy). The handler still requires
// authentication; anonymous users 401.
//
// Filtering: the response includes the firm's own bases AND the
// firm-agnostic ones (firm IS NULL). The Go service-side filter passes
// branding.Name as the firm hint; cross-firm cases (e.g. a future
// non-HLC deployment) get their own filtered slice naturally.

import (
	"net/http"

	"mgit.msbls.de/m/paliad/internal/branding"
	"mgit.msbls.de/m/paliad/internal/services"
)

// submissionBaseRow is the on-the-wire shape returned by the list
// endpoint. Mirrors services.SubmissionBase but drops the raw bytes
// and exposes the parsed section spec inline so the picker can show a
// preview of the default section count without an extra round-trip.
type submissionBaseRow struct {
	ID               string   `json:"id"`
	Slug             string   `json:"slug"`
	Firm             *string  `json:"firm,omitempty"`
	ProceedingFamily *string  `json:"proceeding_family,omitempty"`
	LabelDE          string   `json:"label_de"`
	LabelEN          string   `json:"label_en"`
	DescriptionDE    *string  `json:"description_de,omitempty"`
	DescriptionEN    *string  `json:"description_en,omitempty"`
	GiteaPath        string   `json:"gitea_path"`
	IsDefaultFor     []string `json:"is_default_for"`
	IsActive         bool     `json:"is_active"`
	SectionCount     int      `json:"section_count"`
}

type submissionBaseListResponse struct {
	Bases []submissionBaseRow `json:"bases"`
}

// handleListSubmissionBases backs GET /api/submission-bases.
func handleListSubmissionBases(w http.ResponseWriter, r *http.Request) {
	if !requireDB(w) {
		return
	}
	if _, ok := requireUser(w, r); !ok {
		return
	}
	if dbSvc.submissionBase == nil {
		writeJSON(w, http.StatusServiceUnavailable, map[string]string{
			"error": "submission bases not configured",
		})
		return
	}

	rows, err := dbSvc.submissionBase.List(r.Context(), branding.Name)
	if err != nil {
		writeServiceError(w, err)
		return
	}

	out := make([]submissionBaseRow, 0, len(rows))
	for i := range rows {
		out = append(out, baseRowFromService(&rows[i]))
	}
	writeJSON(w, http.StatusOK, submissionBaseListResponse{Bases: out})
}

// baseRowFromService projects a services.SubmissionBase into the
// on-the-wire row shape.
func baseRowFromService(b *services.SubmissionBase) submissionBaseRow {
	return submissionBaseRow{
		ID:               b.ID.String(),
		Slug:             b.Slug,
		Firm:             b.Firm,
		ProceedingFamily: b.ProceedingFamily,
		LabelDE:          b.LabelDE,
		LabelEN:          b.LabelEN,
		DescriptionDE:    b.DescriptionDE,
		DescriptionEN:    b.DescriptionEN,
		GiteaPath:        b.GiteaPath,
		IsDefaultFor:     b.IsDefaultFor,
		IsActive:         b.IsActive,
		SectionCount:     len(b.SectionSpec.Defaults),
	}
}
