package parlament

import "fmt"

// Event is a parliamentary event from the public schedule.
type Event struct {
	// Date is the ISO-formatted start datetime (e.g. "2025-12-17T13:00:00").
	Date    string
	DateTo  string // end datetime; empty if single-day event
	Title   string
	Type    string // "Terminart" — e.g. "Plenarsitzung", "Ausschusssitzung"
	Venue   string // "Ort" — e.g. "Bundesratssaal"
	Topics  string // "Themen" — JSON-encoded array
	Body    string // "Gremium" — parliamentary body (e.g. "Bundesrat")
	// Path is the portal-relative URL, usable with Client.GetDetail.
	Path string
}

type EventFilter struct {
	// Body filters by parliamentary body name ("Gremium"), e.g. "Nationalrat".
	Body []string
	// EventType filters by event category, e.g. "Plenarsitzung".
	EventType []string
	// DateFrom and DateTo define an inclusive date range (YYYY-MM-DD).
	// Both must be set together; setting only one is a no-op.
	DateFrom string
	DateTo   string
}

// ListEvents returns parliamentary events matching the given filter (dataset 600).
func (c *Client) ListEvents(f EventFilter) ([]Event, int, error) {
	payload := map[string]any{}
	if len(f.Body) > 0 {
		payload["GREMIUM"] = f.Body
	}
	if len(f.EventType) > 0 {
		payload["TERMINART"] = f.EventType
	}
	if f.DateFrom != "" && f.DateTo != "" {
		payload["DATERANGE"] = []string{fmt.Sprintf("%s,%s", f.DateFrom, f.DateTo)}
	}

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

	// Dataset 600 has duplicate column names. colIndex resolves each to its last
	// occurrence: "Datum" → index 15 (ISO datetime), "Terminart" → index 6.
	idx := colIndex(resp.Header)
	events := make([]Event, 0, len(resp.Rows))
	for _, row := range resp.Rows {
		events = append(events, Event{
			Date:   strCol(row, idx, "Datum"),    // last "Datum" = ISO datetime
			DateTo: strCol(row, idx, "Datum Bis"),
			Title:  strCol(row, idx, "Bezeichnung"),
			Type:   strCol(row, idx, "Terminart"),
			Venue:  strCol(row, idx, "Ort"),
			Topics: strCol(row, idx, "Themen"),
			Body:   strCol(row, idx, "Gremium"),
			Path:   strCol(row, idx, "Link"),
		})
	}
	return events, resp.Count, nil
}
