// conditions_read.go executes current-conditions queries.
// Layer: adapters/outbound/postgres conditions feature.
package postgres

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

	"gitea.maximumdirect.net/ejr/weatherapi/internal/app"
)

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

	var row currentConditionsRow
	err := r.db.QueryRowContext(ctx, queryCurrentConditions, observationWindowMinutes).Scan(
		&row.SampleCount,
		&row.TemperatureC,
		&row.ApparentTemperatureC,
		&row.DewpointC,
		&row.RelativeHumidityPercent,
		&row.WindSpeedKmh,
		&row.WindDirectionDegrees,
		&row.ConditionCode,
		&row.IsDay,
	)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("query current conditions: %w", err)
	}

	return mapCurrentConditionsRow(row), nil
}
