package main

import (
	"encoding/json"

	"github.com/1440news/commons"
	"github.com/jackc/pgx/v5"
)

// scanItems scans rows into Item structs
func scanItems(rows pgx.Rows) ([]*shared.Item, error) {
	var items []*shared.Item

	for rows.Next() {
		item := &shared.Item{}
		var guid, title, link, description, content, author *string
		var pubDate, updatedAt, publishedAt *interface{}
		var publishedUri *string
		var enclosureUrl, enclosureType *string
		var enclosureLength *int64
		var imageUrlsJSON, tagsJSON *string

		err := rows.Scan(
			&item.FeedURL, &guid, &title, &link,
			&description, &content, &author, &pubDate,
			&item.DiscoveredAt, &updatedAt,
			&enclosureUrl, &enclosureType, &enclosureLength,
			&imageUrlsJSON, &tagsJSON,
			&publishedAt, &publishedUri,
		)
		if err != nil {
			continue
		}

		item.GUID = shared.StringValue(guid)
		item.Title = shared.StringValue(title)
		item.Link = shared.StringValue(link)
		item.Description = shared.StringValue(description)
		item.Content = shared.StringValue(content)
		item.Author = shared.StringValue(author)
		item.PublishedUri = shared.StringValue(publishedUri)

		if pubDate != nil {
			if t, ok := (*pubDate).(interface{ Time() interface{} }); ok {
				if tm, ok := t.Time().(interface{ IsZero() bool }); ok && !tm.IsZero() {
					// Handle time conversion
				}
			}
		}

		if enclosureUrl != nil && *enclosureUrl != "" {
			item.Enclosure = &shared.Enclosure{
				URL:  *enclosureUrl,
				Type: shared.StringValue(enclosureType),
			}
			if enclosureLength != nil {
				item.Enclosure.Length = *enclosureLength
			}
		}

		if imageUrlsJSON != nil && *imageUrlsJSON != "" {
			json.Unmarshal([]byte(*imageUrlsJSON), &item.ImageURLs)
		}

		if tagsJSON != nil && *tagsJSON != "" {
			json.Unmarshal([]byte(*tagsJSON), &item.Tags)
		}

		items = append(items, item)
	}

	return items, rows.Err()
}
