<?php

namespace App\Master\Models;

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 apiUsage(): HasMany
    {
        return $this->hasMany(ApiUsage::class, 'api_user_id');
    }
}
