use serde::{Deserialize, Serialize};
use steel::*;

use crate::state::auction_pda;

use super::OilAccount;

/// Singleton auction configuration account
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable, Serialize, Deserialize)]
pub struct Auction {
    /// Halving period in seconds (28 days = 2,419,200)
    pub halving_period_seconds: u64,
    
    /// Timestamp of last halving event
    pub last_halving_time: u64,
    
    /// Base mining rates per well (OIL per second, in atomic units)
    /// Significantly lower than Macaron's rates with high differentiation for strategic choices:
    /// - Well 0 (Entry): 0.05 OIL/s = 5,000,000,000 atomic units/s (low rate, accessible)
    /// - Well 1 (Standard): 0.15 OIL/s = 15,000,000,000 atomic units/s (3x Well 0)
    /// - Well 2 (Premium): 0.35 OIL/s = 35,000,000,000 atomic units/s (7x Well 0, 2.3x Well 1)
    /// - Well 3 (Elite): 0.65 OIL/s = 65,000,000,000 atomic units/s (13x Well 0, 4.3x Well 1, 1.9x Well 2)
    /// Total: 1.2 OIL/s (vs Macaron's 4.0 OIL/s) = 70% reduction
    /// Creates meaningful trade-offs: higher rates = higher competition & prices
    pub base_mining_rates: [u64; 4],
    
    /// Auction duration in seconds (1 hour = 3600)
    pub auction_duration_seconds: u64,
    
    /// Starting prices per well (in lamports)
    /// Scaled to match mining rate differentiation for strategic choices:
    /// - Well 0 (Entry): 0.1 SOL = 100,000,000 lamports (lowest price, accessible)
    /// - Well 1 (Standard): 0.2 SOL = 200,000,000 lamports (3x Well 0)
    /// - Well 2 (Premium): 0.3 SOL = 300,000,000 lamports (7x Well 0)
    /// - Well 3 (Elite): 0.4 SOL = 400,000,000 lamports (13x Well 0)
    pub starting_prices: [u64; 4],
    
    /// Minimum contribution to join auction pool (0.01 SOL = 10,000,000 lamports)
    pub min_pool_contribution: u64,
    
    /// Buffer field (for future use)
    pub buffer_a: Numeric,
    
    /// Buffer field (for future use)
    pub buffer_b: u64,
    
    /// Buffer field (for future use)
    pub buffer_c: u64,
    
    /// Buffer field (for future use)
    pub buffer_d: u64,
}

impl Auction {
    pub fn pda() -> (Pubkey, u8) {
        auction_pda()
    }

    /// Check if halving should be applied (returns number of halvings to apply)
    /// Note: Actual halving is applied per EpochState in its check_and_apply_halving method
    pub fn should_apply_halving(&self, clock: &Clock) -> u64 {
        let current_time = clock.unix_timestamp as u64;
        let time_since_last_halving = current_time.saturating_sub(self.last_halving_time);
        
        if time_since_last_halving >= self.halving_period_seconds {
            time_since_last_halving / self.halving_period_seconds
        } else {
            0
        }
    }
}

account!(OilAccount, Auction);

