<?php

namespace App\Models;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Crypt;

class EventPhotoboothSetting extends Model
{
    /** @use HasFactory<\Database\Factories\EventPhotoboothSettingFactory> */
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'enabled' => 'boolean',
        'expires_at' => 'datetime',
        'last_provisioned_at' => 'datetime',
        'last_deprovisioned_at' => 'datetime',
        'last_upload_at' => 'datetime',
        'metadata' => 'array',
        'uploads_last_24h' => 'integer',
        'uploads_total' => 'integer',
    ];

    protected $hidden = [
        'password_encrypted',
    ];

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

    public function getPasswordAttribute(): ?string
    {
        $encrypted = $this->attributes['password_encrypted'] ?? null;

        if (! $encrypted) {
            return null;
        }

        try {
            return Crypt::decryptString($encrypted);
        } catch (DecryptException) {
            return null;
        }
    }

    public function setPasswordAttribute(?string $value): void
    {
        $this->attributes['password_encrypted'] = $value
            ? Crypt::encryptString($value)
            : null;
    }

    public function setUsernameAttribute(?string $value): void
    {
        $this->attributes['username'] = $value ? strtolower($value) : null;
    }
}
