<?php

namespace Shopping\Feed;

use PDO;

class FeedRepository {
    private PDO $dbAdmin;

    public function __construct(PDO $dbAdmin) {
        $this->dbAdmin = $dbAdmin;
    }

    /**
     * Load all feed details indexed by xml_feed_name
     *
     * @return array<string, array>
     */
    public function getAllFeedDetails(): array {
        $sql = "SELECT * FROM feed_campaign_affiliate_mapping";

        $stmt = $this->dbAdmin->query($sql);

        $map = [];

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $map[$row['xml_feed_name']] = $row;
        }

        return $map;
    }

    public function insertShoppingFeedRunHistory(array $data): bool {
        $sql = "
            INSERT INTO shopping_feed_runs_history
            (publisher_id, status, feed_file, notes, published, latest_pointer_updated)
            VALUES
            (:publisher_id, :status, :feed_file, :notes, :published, :latest_pointer_updated)
        ";

        $stmt = $this->dbAdmin->prepare($sql);

        return $stmt->execute([
            ':publisher_id' => $data['publisher_id'],
            ':status' => $data['status'], // SUCCESS or FAILED
            ':feed_file' => $data['feed_file'] ?? null,
            ':notes' => $data['notes'] ?? null,
            ':published' => $data['published'] ?? 0,
            ':latest_pointer_updated' => $data['latest_pointer_updated'] ?? 0,
        ]);
    }
}