// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.

// LP181 implements the epoch logic specified here:
// https://github.com/luxfi/LPs/blob/main/LPs/181-p-chain-epoched-views/README.md
package lp181

import (
	"time"

	"github.com/luxfi/node/upgrade"
	"github.com/luxfi/node/vms/proposervm/block"
)

// NewEpoch returns a child block's epoch based on its parent.
func NewEpoch(
	upgrades upgrade.Config,
	parentPChainHeight uint64,
	parentEpoch block.Epoch,
	parentTimestamp time.Time,
	_ time.Time,
) block.Epoch {
	if parentEpoch == (block.Epoch{}) {
		// If the parent was not assigned an epoch, then the child is the first
		// block of the initial epoch.
		return block.Epoch{
			PChainHeight: parentPChainHeight,
			Number:       1,
			StartTime:    parentTimestamp.Unix(),
		}
	}

	epochEndTime := time.Unix(parentEpoch.StartTime, 0).Add(upgrades.EpochDuration)
	if parentTimestamp.Before(epochEndTime) {
		// If the parent was issued before the end of its epoch, then it did not
		// seal the epoch.
		return parentEpoch
	}

	// The parent sealed the epoch, so the child is the first block of the new
	// epoch.
	return block.Epoch{
		PChainHeight: parentPChainHeight,
		Number:       parentEpoch.Number + 1,
		StartTime:    parentTimestamp.Unix(),
	}
}
