package parlament

// PressRelease is a parliamentary correspondence item (Parlamentskorrespondenz).
type PressRelease struct {
	// Date is the ISO-formatted publication date (e.g. "2025-12-30T00:00:00").
	Date     string
	Number   string // e.g. "PK1235"
	Title    string
	Subtitle string
	Topics   string // "Abo-Themen" — JSON-encoded array, e.g. ["Bildung"]
	Keywords string // "Stichworte" — JSON-encoded array of finer-grained tags
	// Path is the portal-relative URL, usable with Client.GetDetail.
	Path string
}

type PressReleaseFilter struct {
	// Year filters by publication year, e.g. "2025".
	Year []string
	// Topics filters by broad subject area.
	Topics []string
	// Keywords filters by finer-grained subject tags ("STW").
	Keywords []string
}

// ListPressReleases returns parliamentary press releases matching the filter (dataset 110).
func (c *Client) ListPressReleases(f PressReleaseFilter) ([]PressRelease, int, error) {
	payload := map[string]any{}
	if len(f.Year) > 0 {
		payload["JAHR"] = f.Year
	}
	if len(f.Topics) > 0 {
		payload["THEMEN"] = f.Topics
	}
	if len(f.Keywords) > 0 {
		payload["STW"] = f.Keywords
	}

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

	// Dataset 110 has duplicate column names. colIndex resolves each to its last
	// occurrence: "Datum" → index 11 (ISO date), "Titel" → index 5 (clean plain text).
	idx := colIndex(resp.Header)
	releases := make([]PressRelease, 0, len(resp.Rows))
	for _, row := range resp.Rows {
		releases = append(releases, PressRelease{
			Date:     strCol(row, idx, "Datum"),    // last "Datum" = ISO date
			Number:   strCol(row, idx, "Nr."),
			Title:    strCol(row, idx, "Titel"),    // last "Titel" = plain text
			Subtitle: strCol(row, idx, "Untertitel"),
			Topics:   strCol(row, idx, "Abo-Themen"),
			Keywords: strCol(row, idx, "Stichworte"),
			Path:     strCol(row, idx, "Link"),
		})
	}
	return releases, resp.Count, nil
}
