<?php

namespace App\Models;

use App\Models\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * One published version of the data-processing agreement.
 *
 * The TEXT is not this application's. An operator uploads the document their
 * lawyer wrote, names the version, and publishes it; everything here is about
 * serving that file and knowing which one is in force. The technical and
 * organisational measures ride along as a second file rather than as a second
 * concept — they are an annex to the agreement, and "which measures applied when
 * this customer accepted" has to have one answer.
 */
class DpaVersion extends Model
{
    use HasFactory, HasUuid;

    protected $fillable = ['version', 'agreement_path', 'measures_path', 'note', 'published_at', 'created_by'];

    protected function casts(): array
    {
        return ['published_at' => 'datetime'];
    }

    /**
     * The version in force: the newest published one.
     *
     * Newest by publication, not by id — a version prepared earlier and
     * published later is the later one, and the id says nothing about that.
     */
    public static function current(): ?self
    {
        return static::query()
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->latest('published_at')
            ->first();
    }

    public function isPublished(): bool
    {
        return $this->published_at !== null && $this->published_at->isPast();
    }

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

    public function operator()
    {
        return $this->belongsTo(Operator::class, 'created_by');
    }
}
