<?php

namespace App\Models;

use App\Domain\Study\StudyAccessFlags;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SharedStudy extends BaseModel
{
    public function study(): BelongsTo
    {
        return $this->belongsTo(Study::class);
    }

    public function recipient(): BelongsTo
    {
        return $this->belongsTo(User::class, 'recipient_id');
    }

    public function sender(): BelongsTo
    {
        return $this->belongsTo(User::class, 'sender_id');
    }

    public function isPasswordProtected(): bool
    {
        return ! blank($this->access_password);
    }

    public function attempt(string $password): bool
    {
        if (! $this->isPasswordProtected()) {
            return true;
        }

        return strcmp($this->access_password, $password) === 0;
    }

    public function hasExpired(): bool
    {
        if (blank($this->expires_at)) {
            return false;
        }

        return $this->expires_at->isPast();
    }

    protected function casts(): array
    {
        return [
            'expires_at' => 'datetime',
            'access_flags' => StudyAccessFlags::class,
        ];
    }
}