<?php

namespace App\Models;

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

class PlanUsage extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'plan_id',
        'plan_feature_id',
        'usage_amount',
        'usage_type',
        'period_start',
        'period_end',
        'metadata',
        'subscription_id',
        'period_type',
        'created_at',
        'usage_value',
        'updated_at',
    ];

    protected $casts = [
        'usage_amount' => 'decimal:2',
        'period_start' => 'date',
        'period_end' => 'date',
        'metadata' => 'array',
    ];

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

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

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

    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function scopeByPeriod($query, $startDate, $endDate)
    {
        return $query->where('period_start', $startDate)
            ->where('period_end', $endDate);
    }

    public function scopeMonthly($query)
    {
        return $query->where('usage_type', 'monthly');
    }

    public function incrementUsage(float $amount = 1): void
    {
        $this->increment('usage_amount', $amount);
    }

    public function resetUsage(): void
    {
        $this->update(['usage_amount' => 0]);
    }
}
