<?php

declare(strict_types=1);

namespace App\Models;

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

class OperationalControlActivation extends Model
{
    /** @use HasFactory<OperationalControlActivationFactory> */
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'expires_at' => 'datetime',
    ];

    protected static function newFactory(): OperationalControlActivationFactory
    {
        return OperationalControlActivationFactory::new();
    }

    public function workspace(): BelongsTo
    {
        return $this->belongsTo(Workspace::class);
    }

    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(PlatformUser::class, 'created_by_platform_user_id');
    }

    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(PlatformUser::class, 'updated_by_platform_user_id');
    }

    public function scopeForControl(Builder $query, string $controlKey): Builder
    {
        return $query->where('control_key', trim($controlKey));
    }

    public function scopeForGlobalScope(Builder $query): Builder
    {
        return $query->where('scope_type', 'global');
    }

    public function scopeForWorkspaceScope(Builder $query, int|Workspace $workspace): Builder
    {
        $workspaceId = $workspace instanceof Workspace
            ? (int) $workspace->getKey()
            : (int) $workspace;

        return $query
            ->where('scope_type', 'workspace')
            ->where('workspace_id', $workspaceId);
    }

    public function scopeNotExpired(Builder $query): Builder
    {
        return $query->where(function (Builder $query): void {
            $query
                ->whereNull('expires_at')
                ->orWhere('expires_at', '>', now());
        });
    }
}