package parlament

// CommitteeMembership records a person's role on a parliamentary committee.
type CommitteeMembership struct {
	Period     string // legislative period, e.g. "XXVIII"
	Role       string // "Funktion" — e.g. "Mitglied", "Obmann"
	Committee  string // short committee name, e.g. "Hauptausschuss"
	Chamber    string // "nrbr" — "NR" or "BR"
	Body       string // "Gremium" — full body name, e.g. "Nationalrat"
	PersonID   string // "PAD_INTERN" — internal numeric person identifier
	FromDate   string // "fromDate" — ISO-style timestamp of membership start
	// Path is the portal-relative URL for the committee, usable with Client.GetDetail.
	Path string // "URL" column
}

type CommitteeMembershipFilter struct {
	// Period filters by legislative period, e.g. "XXVIII".
	Period []string
	// PersonID filters by the internal person identifier ("PAD_INTERN").
	PersonID []string
	// Committee filters by committee name.
	Committee []string
	// Chamber filters by chamber: "NR" or "BR".
	Chamber []string
}

// ListCommitteeMemberships returns committee membership records (dataset 250).
func (c *Client) ListCommitteeMemberships(f CommitteeMembershipFilter) ([]CommitteeMembership, int, error) {
	payload := map[string]any{}
	if len(f.Period) > 0 {
		payload["GP"] = f.Period
	}
	if len(f.PersonID) > 0 {
		payload["PAD_INTERN"] = f.PersonID
	}
	if len(f.Committee) > 0 {
		payload["AUSSCHUSS"] = f.Committee
	}
	if len(f.Chamber) > 0 {
		payload["NRBR"] = f.Chamber
	}

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

	// "Ausschuss" appears twice: index 3 has the name with date "(24.10.2024)",
	// index 8 has the short name without date. colIndex picks the last (index 8).
	idx := colIndex(resp.Header)
	memberships := make([]CommitteeMembership, 0, len(resp.Rows))
	for _, row := range resp.Rows {
		memberships = append(memberships, CommitteeMembership{
			Period:    strCol(row, idx, "GP"),
			Role:      strCol(row, idx, "Funktion"),
			Committee: strCol(row, idx, "Ausschuss"), // last occurrence = short name
			Chamber:   strCol(row, idx, "nrbr"),
			Body:      strCol(row, idx, "Gremium"),
			PersonID:  strCol(row, idx, "PAD_INTERN"),
			FromDate:  strCol(row, idx, "fromDate"),
			Path:      strCol(row, idx, "URL"),
		})
	}
	return memberships, resp.Count, nil
}
