<?php

namespace App\Nexus\Models;

use Illuminate\Database\Eloquent\Model;

class NexusAuditLog extends Model
{
    protected $table = 'nexus_audit_log';

    // Audit log is append-only — no updates ever
    public $timestamps = false;

    protected $fillable = [
        'event',
        'actor_type',
        'actor_id',
        'subject_user_id',
        'nexus_session_id',
        'sell_id',
        'bid_id',
        'context',
        'notes',
        'created_at',
    ];

    protected $casts = [
        'context'    => 'array',
        'created_at' => 'datetime',
    ];

    // ─── ACTOR TYPE CONSTANTS ───
    const ACTOR_SYSTEM    = 'system';
    const ACTOR_ADMIN     = 'admin';
    const ACTOR_SCHEDULER = 'scheduler';

    // ─── EVENT CONSTANTS ───
    const EVENT_SESSION_STARTED     = 'session.started';
    const EVENT_SESSION_COMPLETED   = 'session.completed';
    const EVENT_SESSION_CANCELLED   = 'session.cancelled';
    const EVENT_SELL_APPROVED       = 'sell.approved';
    const EVENT_SELL_REJECTED       = 'sell.rejected';
    const EVENT_CONFIG_CHANGED      = 'config.changed';
    const EVENT_ENGINE_ACTIVATED    = 'engine.activated';
    const EVENT_ENGINE_PAUSED       = 'engine.paused';
    const EVENT_LOGIN_SUCCESS       = 'admin.login.success';
    const EVENT_LOGIN_FAILED        = 'admin.login.failed';
    const EVENT_MONTHLY_RESET       = 'metrics.monthly_reset';

    // ─── RELATIONSHIPS ───

    public function session()
    {
        return $this->belongsTo(NexusSession::class, 'nexus_session_id');
    }

    // ─── SCOPES ───

    public function scopeForSession($query, int $sessionId)
    {
        return $query->where('nexus_session_id', $sessionId);
    }

    public function scopeForUser($query, int $userId)
    {
        return $query->where('subject_user_id', $userId);
    }

    public function scopeEvent($query, string $event)
    {
        return $query->where('event', $event);
    }

    // ─── STATIC WRITE METHODS ───
    // All writes go through NexusAuditLogger — do not call create() directly

    protected static function boot()
    {
        parent::boot();
        // Force created_at on insert since timestamps = false
        static::creating(function ($model) {
            if (empty($model->created_at)) {
                $model->created_at = now();
            }
        });
    }
}
