<?php

namespace App\Models;

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

class SocialAccount extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'provider',
        'provider_id',
        'provider_token',
        'provider_refresh_token',
        'token_expires_at',
        'provider_email',
        'provider_name',
        'provider_avatar',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'token_expires_at' => 'datetime',
    ];

    /**
     * Supported providers.
     */
    const PROVIDER_GOOGLE = 'google';
    const PROVIDER_FACEBOOK = 'facebook';
    const PROVIDER_GITHUB = 'github';

    /**
     * Get the user that owns the social account.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Find a social account by provider and provider ID.
     *
     * @param string $provider
     * @param string $providerId
     * @return self|null
     */
    public static function findByProvider(string $provider, string $providerId): ?self
    {
        return self::where('provider', $provider)
            ->where('provider_id', $providerId)
            ->first();
    }

    /**
     * Check if token is expired.
     *
     * @return bool
     */
    public function isTokenExpired(): bool
    {
        return $this->token_expires_at && $this->token_expires_at->isPast();
    }

    /**
     * Get supported providers.
     *
     * @return array
     */
    public static function getSupportedProviders(): array
    {
        return [
            self::PROVIDER_GOOGLE,
            self::PROVIDER_FACEBOOK,
            self::PROVIDER_GITHUB,
        ];
    }
}
