using System.Collections.Generic;
using System.Threading.Tasks;
using QuantEngine.Core.Interfaces;
using QuantEngine.Core.Models;

namespace QuantEngine.Application.Services
{
    public class CollectionService
    {
        private readonly IPostgresqlHistoryStore _historyStore;

        public CollectionService(IPostgresqlHistoryStore historyStore)
        {
            _historyStore = historyStore;
        }

        public Task<int> AppendRunAsync(CollectionRun run)
            => _historyStore.AppendAsync("collection_run_history", new Dictionary<string, object?>
            {
                ["run_id"] = run.RunId,
                ["collector_name"] = run.CollectorName,
                ["started_at"] = run.StartedAt,
                ["finished_at"] = run.FinishedAt,
                ["status"] = run.Status,
                ["input_source"] = run.InputSource,
                ["output_json_path"] = run.OutputJsonPath,
                ["output_db_path"] = run.OutputDbPath,
                ["notes"] = run.Notes,
                ["created_at"] = run.CreatedAt
            });

        public Task<int> AppendSnapshotAsync(CollectionSnapshot snapshot)
            => _historyStore.AppendAsync("collection_snapshot_history", new Dictionary<string, object?>
            {
                ["run_id"] = snapshot.RunId,
                ["dataset_name"] = snapshot.DatasetName,
                ["ticker"] = snapshot.Ticker,
                ["name"] = snapshot.Name,
                ["sector"] = snapshot.Sector,
                ["as_of_date"] = snapshot.AsOfDate,
                ["source_priority"] = snapshot.SourcePriority,
                ["source_status"] = snapshot.SourceStatus,
                ["payload_json"] = snapshot.PayloadJson,
                ["provenance_json"] = snapshot.ProvenanceJson,
                ["created_at"] = snapshot.CreatedAt
            });

        public Task<int> AppendSourceErrorAsync(CollectionSourceError error)
            => _historyStore.AppendAsync("collection_source_error_history", new Dictionary<string, object?>
            {
                ["run_id"] = error.RunId,
                ["ticker"] = error.Ticker,
                ["source_name"] = error.SourceName,
                ["error_kind"] = error.ErrorKind,
                ["error_message"] = error.ErrorMessage,
                ["payload_json"] = error.PayloadJson,
                ["created_at"] = error.CreatedAt
            });
    }
}
