<?php

namespace Technical\Integrations\Models;

use Functional\Users\Models\User;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Technical\Integrations\Database\Factories\IntegrationFactory;
use Technical\Integrations\Enums\IntegrationStatus;

/**
 * Compte connecté d'un utilisateur chez un fournisseur externe (Garmin/Strava/...).
 * Couche générique : ne référence jamais un fournisseur en dur, seulement sa clé (provider).
 *
 * @property string $provider
 * @property string|null $external_user_id
 * @property string|null $access_token
 * @property string|null $refresh_token
 * @property \Illuminate\Support\Carbon|null $token_expires_at
 * @property array|null $scopes
 * @property IntegrationStatus $status
 * @property \Illuminate\Support\Carbon $connected_at
 * @property \Illuminate\Support\Carbon|null $last_synced_at
 * @property array|null $meta
 */
#[UseFactory(IntegrationFactory::class)]
class Integration extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'provider', 'external_user_id', 'access_token', 'refresh_token',
        'token_expires_at', 'scopes', 'status', 'connected_at', 'last_synced_at', 'meta',
    ];

    protected $casts = [
        'access_token' => 'encrypted',
        'refresh_token' => 'encrypted',
        'token_expires_at' => 'datetime',
        'scopes' => 'array',
        'status' => IntegrationStatus::class,
        'connected_at' => 'datetime',
        'last_synced_at' => 'datetime',
        'meta' => 'array',
    ];

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

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