// discussion_read.go executes forecast discussion queries.
// Layer: adapters/outbound/postgres discussion feature.
package postgres

import (
	"context"
	"database/sql"
	"errors"
	"fmt"

	"gitea.maximumdirect.net/ejr/weatherfeeder/model"
)

func (r *Repository) LatestForecastDiscussion(ctx context.Context) (*model.WeatherForecastDiscussion, error) {
	if r == nil || r.db == nil {
		return nil, fmt.Errorf("postgres repository is not configured")
	}

	var row discussionParentRow
	err := r.db.QueryRowContext(ctx, queryLatestForecastDiscussion).Scan(
		&row.EventID,
		&row.OfficeID,
		&row.OfficeName,
		&row.IssuedAt,
		&row.UpdatedAt,
		&row.Product,
		&row.ShortTermQualifier,
		&row.ShortTermIssuedAt,
		&row.ShortTermText,
		&row.LongTermQualifier,
		&row.LongTermIssuedAt,
		&row.LongTermText,
	)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("query latest forecast discussion: %w", err)
	}

	run := mapDiscussionParentRow(row)

	keyMessages, err := r.loadForecastDiscussionKeyMessages(ctx, row.EventID)
	if err != nil {
		return nil, err
	}
	run.KeyMessages = keyMessages

	return &run, nil
}

func (r *Repository) loadForecastDiscussionKeyMessages(ctx context.Context, eventID string) ([]string, error) {
	rows, err := r.db.QueryContext(ctx, queryForecastDiscussionKeyMessages, eventID)
	if err != nil {
		return nil, fmt.Errorf("query forecast discussion key messages: %w", err)
	}
	defer rows.Close()

	out := make([]string, 0)
	for rows.Next() {
		var row discussionKeyMessageRow
		if err := rows.Scan(
			&row.MessageIndex,
			&row.MessageText,
		); err != nil {
			return nil, fmt.Errorf("scan forecast discussion key message row: %w", err)
		}
		out = append(out, mapDiscussionKeyMessageRow(row))
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterate forecast discussion key message rows: %w", err)
	}
	return out, nil
}
