<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Gallery extends Model
{
    /** @use HasFactory<\Database\Factories\GalleryFactory> */
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'title',
        'images_path',
        'is_public',
        'allow_ai_styles',
        'allow_print',
        'require_password',
        'password_hash',
        'expires_at',
        'access_duration_minutes',
        'upload_enabled',
        'upload_token_hash',
        'upload_token_expires_at',
        'sparkbooth_username',
        'sparkbooth_password',
        'sparkbooth_response_format',
    ];

    protected function casts(): array
    {
        return [
            'is_public' => 'bool',
            'allow_ai_styles' => 'bool',
            'allow_print' => 'bool',
            'require_password' => 'bool',
            'expires_at' => 'datetime',
            'access_duration_minutes' => 'int',
            'upload_enabled' => 'bool',
            'upload_token_expires_at' => 'datetime',
            'sparkbooth_password' => 'encrypted',
            'sparkbooth_response_format' => 'string',
        ];
    }

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

    public function setUploadToken(string $token): void
    {
        $this->upload_token_hash = \Illuminate\Support\Facades\Hash::make($token);
    }

    public function regenerateUploadToken(): string
    {
        $token = \Illuminate\Support\Str::random(40);
        $this->setUploadToken($token);
        $this->save();

        return $token;
    }

    public function regenerateSparkboothPassword(): string
    {
        $password = \Illuminate\Support\Str::random(24);
        $this->sparkbooth_password = $password;
        $this->save();

        return $password;
    }

    public function clearSparkboothConnection(): void
    {
        $this->forceFill([
            'upload_token_hash' => null,
            'upload_token_expires_at' => null,
            'sparkbooth_username' => null,
            'sparkbooth_password' => null,
            'upload_enabled' => false,
        ])->save();
    }
}
