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) ([]*commons.Item, error) {
	var items []*commons.Item

	for rows.Next() {
		item := &commons.Item{}
		var guid, title, link, description, content, author *string
		var pubDate, updatedAt, publishedAt *interface{}
		var status, 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,
			&status, &publishedAt, &publishedUri,
		)
		if err != nil {
			continue
		}

		item.GUID = commons.StringValue(guid)
		item.Title = commons.StringValue(title)
		item.Link = commons.StringValue(link)
		item.Description = commons.StringValue(description)
		item.Content = commons.StringValue(content)
		item.Author = commons.StringValue(author)
		item.Status = commons.StringValue(status)
		item.PublishedUri = commons.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 = &commons.Enclosure{
				URL:  *enclosureUrl,
				Type: commons.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()
}
