package gateway

import (
	"context"
	"time"

	"github.com/acp/interceptor/internal/approval"
	"github.com/acp/interceptor/internal/audit"
	"github.com/acp/interceptor/internal/config"
	"github.com/acp/interceptor/internal/registry"
	"github.com/acp/interceptor/internal/storage/postgres"
)

type platformStores struct {
	events    audit.EventStore
	approvals approval.Repository
	agents    registry.Repository
}

func initPlatformStores(cfg config.Config) (platformStores, func(), error) {
	if cfg.DatabaseURL == "" {
		memAgents := registry.NewMemoryStore()
		if cfg.SeedDemoAgents {
			memAgents.SeedDemoAgents()
		}
		return platformStores{
			events:    audit.NewStore(500),
			approvals: approval.NewStore(500),
			agents:    memAgents,
		}, func() {}, nil
	}

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	pool, err := postgres.Open(ctx, cfg.DatabaseURL)
	if err != nil {
		return platformStores{}, nil, err
	}
	if err := postgres.Migrate(ctx, pool); err != nil {
		pool.Close()
		return platformStores{}, nil, err
	}

	cleanup := func() { pool.Close() }
	return platformStores{
		events:    postgres.NewAuditStore(pool),
		approvals: postgres.NewApprovalStore(pool),
		agents:    postgres.NewAgentStore(pool),
	}, cleanup, nil
}
