<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Lead extends Model
{
    protected $guarded = [];

    protected $casts = [
        'reviewed_at' => 'datetime',
        'points_reversed_at' => 'datetime',
        'original_points' => 'float',
        'credited_points' => 'float',
    ];

    protected static function booted(): void
    {
        static::creating(function (Lead $lead) {
            if ($lead->original_points === null) {
                $lead->original_points = $lead->points;
            }

            if (!$lead->isDirty('credited_points')) {
                $lead->credited_points = $lead->status === 'approved' && !$lead->points_reversed_at
                    ? $lead->points
                    : 0;
            }
        });
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function reviewer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reviewed_by');
    }

    public function adjustments(): HasMany
    {
        return $this->hasMany(LeadAdjustment::class)->latest();
    }
}
