package parlament

// ParticipatoryType distinguishes citizen-participation item categories.
type ParticipatoryType string

const (
	ParticipatoryMinisterialDraft ParticipatoryType = "MEG" // Ministerialentwurf (public consultation)
	ParticipatoryPetition         ParticipatoryType = "PET" // Petition
	ParticipatoryInitiative       ParticipatoryType = "BIG" // Bürgerinitiative (citizen initiative)
)

// ParticipatoryItem is a participatory democracy item: a public consultation,
// petition, or citizen initiative open for comment or signature collection.
type ParticipatoryItem struct {
	Period      string
	Date        string // "Datum" — display date, e.g. "04.05.2026"
	Title       string // "Betreff"
	Number      string // "Nr." — e.g. "101/ME"
	Type        string // "DOKTYP" — e.g. "MEG", "PET", "BIG"
	Category    string // "Gegenstand" — human-readable type, e.g. "Ministerialentwurf"
	Supporters  string // "Unterstützungen" — signature count (as string)
	Statements  string // "Stellungnahmen" — submitted opinions count
	Topics      string // "Themen" — JSON-encoded array
	Active      bool   // "Aktiv?" == "J"
	// Path is the portal-relative URL, usable with Client.GetDetail.
	Path string // "b" column
}

type ParticipatoryFilter struct {
	// Active, when true, restricts to items currently open for participation.
	Active bool
	// Period filters by legislative period, e.g. "XXVIII".
	Period []string
	// Type filters by document category (e.g. ParticipatoryPetition).
	Type []ParticipatoryType
	// Topics filters by subject area.
	Topics []string
}

// ListParticipatoryItems returns participatory democracy items (dataset 143).
func (c *Client) ListParticipatoryItems(f ParticipatoryFilter) ([]ParticipatoryItem, int, error) {
	payload := map[string]any{}
	if f.Active {
		payload["AKTIV"] = []string{"J"}
	}
	if len(f.Period) > 0 {
		payload["GP_CODE"] = f.Period
	}
	if len(f.Type) > 0 {
		types := make([]string, len(f.Type))
		for i, t := range f.Type {
			types[i] = string(t)
		}
		payload["DOKTYP"] = types
	}
	if len(f.Topics) > 0 {
		payload["THEMEN"] = f.Topics
	}

	resp, err := c.postDataset(143, payload)
	if err != nil {
		return nil, 0, err
	}

	idx := colIndex(resp.Header)
	items := make([]ParticipatoryItem, 0, len(resp.Rows))
	for _, row := range resp.Rows {
		items = append(items, ParticipatoryItem{
			Period:     strCol(row, idx, "GP_CODE"),
			Date:       strCol(row, idx, "Datum"),
			Title:      strCol(row, idx, "Betreff"),
			Number:     strCol(row, idx, "Nr."),
			Type:       strCol(row, idx, "DOKTYP"),
			Category:   strCol(row, idx, "Gegenstand"),
			Supporters: strCol(row, idx, "Unterstützungen"),
			Statements: strCol(row, idx, "Stellungnahmen"),
			Topics:     strCol(row, idx, "Themen"),
			Active:     strCol(row, idx, "Aktiv?") == "J",
			Path:       strCol(row, idx, "b"),
		})
	}
	return items, resp.Count, nil
}
