<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Activitylog\Traits\CausesActivity;

class User extends Authenticatable
{
    use HasFactory, Notifiable, TwoFactorAuthenticatable, HasRoles, CausesActivity;

    protected $fillable = [
        'name',
        'email',
        'password',
        'avatar',
        'bio',
        'google_access_token',
        'google_refresh_token',
        'google_token_expires_at',
        'google_calendar_id',
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_secret',
        'two_factor_recovery_codes',
        'google_access_token',
        'google_refresh_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at'       => 'datetime',
            'password'                => 'hashed',
            'two_factor_confirmed_at' => 'datetime',
            'google_access_token'     => 'encrypted',
            'google_refresh_token'    => 'encrypted',
            'google_token_expires_at' => 'integer',
        ];
    }

    public function jobPostings()
    {
        return $this->hasMany(JobPosting::class, 'created_by');
    }

    public function reviewedApplications()
    {
        return $this->hasMany(JobApplication::class, 'reviewed_by');
    }

    public function hasGoogleCalendar(): bool
    {
        try {
            return !empty($this->google_access_token) || !empty($this->google_refresh_token);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            // Eski şifrelenmemiş token varsa bozuk sayılır, bağlantı yok kabul et
            return false;
        }
    }
}
