<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SystemAccount extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'account_type',
        'balance',
        'currency',
        'status',
        'configurations',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'balance' => 'decimal:8',
        'configurations' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // Account types
    const TYPE_MARKET_MAKER = 'market_maker';
    const TYPE_LIQUIDITY_POOL = 'liquidity_pool';
    const TYPE_RESERVE = 'reserve';
    const TYPE_INSURANCE = 'insurance';

    // Status constants
    const STATUS_ACTIVE = 'active';
    const STATUS_PAUSED = 'paused';
    const STATUS_ARCHIVED = 'archived';

    /**
     * Get account by type
     */
    public static function getByType(string $type): ?self
    {
        return self::where('account_type', $type)->first();
    }

    /**
     * Create system account if it doesn't exist
     */
    public static function createAccount(string $type, string $name, string $currency = 'KES', array $config = []): self
    {
        $existing = self::where('account_type', $type)->first();
        
        if ($existing) {
            return $existing;
        }

        return self::create([
            'name' => $name,
            'account_type' => $type,
            'balance' => 0,
            'currency' => $currency,
            'status' => self::STATUS_ACTIVE,
            'configurations' => $config,
        ]);
    }

    /**
     * Add funds to system account
     */
    public function addFunds(float $amount, string $description = ''): bool
    {
        if ($amount <= 0) {
            return false;
        }

        $this->increment('balance', $amount);
        $this->logTransaction('credit', $amount, $description);
        return true;
    }

    /**
     * Deduct funds from system account
     */
    public function deductFunds(float $amount, string $description = ''): bool
    {
        if ($amount <= 0 || $this->balance < $amount) {
            return false;
        }

        $this->decrement('balance', $amount);
        $this->logTransaction('debit', $amount, $description);
        return true;
    }

    /**
     * Get account balance
     */
    public function getBalance(): float
    {
        return $this->balance;
    }

    /**
     * Check if account has sufficient funds
     */
    public function hasSufficientFunds(float $amount): bool
    {
        return $this->balance >= $amount;
    }

    /**
     * Activate account
     */
    public function activate(): bool
    {
        $this->status = self::STATUS_ACTIVE;
        return $this->save();
    }

    /**
     * Pause account
     */
    public function pause(): bool
    {
        $this->status = self::STATUS_PAUSED;
        return $this->save();
    }

    /**
     * Log transaction
     */
    private function logTransaction(string $type, float $amount, string $description = ''): void
    {
        // In a real implementation, this would log to a separate table
        \Log::info("System account transaction", [
            'account_id' => $this->id,
            'account_type' => $this->account_type,
            'type' => $type,
            'amount' => $amount,
            'balance_after' => $this->balance,
            'description' => $description,
            'timestamp' => now(),
        ]);
    }

    /**
     * Get configuration value
     */
    public function getConfig(string $key, $default = null)
    {
        return $this->configurations[$key] ?? $default;
    }

    /**
     * Set configuration value
     */
    public function setConfig(string $key, $value): bool
    {
        $config = $this->configurations ?? [];
        $config[$key] = $value;
        $this->configurations = $config;
        return $this->save();
    }

    /**
     * Scope for active accounts
     */
    public function scopeActive($query)
    {
        return $query->where('status', self::STATUS_ACTIVE);
    }

    /**
     * Scope for specific account type
     */
    public function scopeOfType($query, string $type)
    {
        return $query->where('account_type', $type);
    }
}