<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class CalendarIntegration extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'provider',
        'provider_email',
        'calendar_id',
        'calendar_name',
        'access_token',
        'refresh_token',
        'token_expires_at',
        'sync_mode',
        'sync_token',
        'last_synced_at',
        'watch_channel_id',
        'watch_resource_id',
        'watch_expires_at',
    ];

    protected $casts = [
        'token_expires_at' => 'datetime',
        'last_synced_at'   => 'datetime',
        'watch_expires_at' => 'datetime',
    ];

    protected $hidden = [
        'access_token',
        'refresh_token',
        'sync_token',
    ];

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

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

    public function isExpired(): bool
    {
        return $this->token_expires_at && $this->token_expires_at->isPast();
    }

    /** Gibt den access_token unverschlüsselt zurück (umgeht $hidden). */
    public function rawAccessToken(): ?string
    {
        return $this->getRawOriginal('access_token');
    }

    /** Gibt den sync_token zurück (umgeht $hidden). */
    public function rawSyncToken(): ?string
    {
        return $this->getRawOriginal('sync_token');
    }
}
