<?php

namespace App\Models;

use App\Enums\SubscriptionStatus;
use App\Models\Concerns\BelongsToCompany;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Subscription extends Model
{
    use HasFactory, SoftDeletes, BelongsToCompany;

    protected $fillable = [
        'company_id', 'plan_id',
        'status', 'billing_cycle',
        'amount', 'currency',
        'trial_starts_at', 'trial_ends_at',
        'current_period_start', 'current_period_end',
        'cancelled_at', 'ended_at',
        'coupon_code', 'discount_amount',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'status'                => SubscriptionStatus::class,
            'amount'                => 'decimal:2',
            'discount_amount'       => 'decimal:2',
            'trial_starts_at'       => 'datetime',
            'trial_ends_at'         => 'datetime',
            'current_period_start'  => 'datetime',
            'current_period_end'    => 'datetime',
            'cancelled_at'          => 'datetime',
            'ended_at'              => 'datetime',
            'metadata'              => 'array',
        ];
    }

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

    public function payments(): HasMany
    {
        return $this->hasMany(SubscriptionPayment::class);
    }

    public function scopeActive(Builder $q): Builder
    {
        return $q->whereIn('status', ['trial', 'active']);
    }

    public function scopeExpiringSoon(Builder $q, int $days = 7): Builder
    {
        return $q->active()
            ->whereBetween('current_period_end', [now(), now()->addDays($days)]);
    }

    public function isOnTrial(): bool
    {
        return $this->status === SubscriptionStatus::Trial
            && $this->trial_ends_at?->isFuture();
    }

    public function daysUntilExpiration(): ?int
    {
        return $this->current_period_end?->diffInDays(now(), false) * -1;
    }
}
