<?php

namespace App\Master\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Mtc\MercuryDataModels\ApiUsage;
use Mtc\MercuryDataModels\Tenant;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class ApiUser extends Model
{
    use CentralConnection;
    use HasFactory;

    protected $fillable = [
        'name',
        'is_active',
        'client_id',
        'client_secret',
        'previous_client_id',
        'previous_client_secret',
        'previous_credentials_expires_at',
        'token_type',
        'credentials_last_updated_at',
        'credentials_due_for_update_at',
        'notes',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'credentials_last_updated_at' => 'datetime',
        'credentials_due_for_update_at' => 'datetime',
        'previous_credentials_expires_at' => 'datetime',
    ];

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

    public function tenants(): BelongsToMany
    {
        return $this->belongsToMany(Tenant::class, 'api_user_tenants');
    }

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

    public function apiUsage(): HasMany
    {
        return $this->hasMany(ApiUsage::class, 'api_user_id');
    }

    /**
     * The date the user's credentials next need renewing, regardless of auth type.
     * OAuth users rotate their client secret (credentials_due_for_update_at); persistent
     * token users renew when their longest-lived token expires.
     */
    public function getCredentialExpiresAtAttribute(): ?Carbon
    {
        if ($this->token_type === ApiToken::TYPE_OAUTH) {
            return $this->credentials_due_for_update_at;
        }

        return $this->tokens->sortByDesc('expires_at')->first()?->expires_at;
    }

    /**
     * Whole days until the credentials in getCredentialExpiresAtAttribute() expire.
     * Negative once expired, null when there is nothing to renew yet.
     */
    public function getCredentialExpiresInDaysAttribute(): ?int
    {
        $expiresAt = $this->credential_expires_at;

        return $expiresAt === null ? null : (int) round(Carbon::now()->diffInDays($expiresAt, false));
    }
}
