<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

class Keystore extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'alias',
        'encrypted_keystore',
        'encrypted_password',
        'encrypted_key_password',
    ];

    /**
     * Get the user that owns the keystore.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the apps using this keystore.
     * Note: Since keystores are stored in platform_config JSON,
     * this is a manual query rather than a traditional relationship.
     */
    public function apps()
    {
        return App::whereJsonContains('platform_config->keystore_id', $this->id)->get();
    }

    /**
     * Encrypt and set the keystore data.
     */
    public function setKeystoreData(string $keystoreContent): void
    {
        $this->encrypted_keystore = Crypt::encryptString(base64_encode($keystoreContent));
    }

    /**
     * Decrypt and get the keystore data.
     */
    public function getKeystoreData(): string
    {
        return base64_decode(Crypt::decryptString($this->encrypted_keystore));
    }

    /**
     * Encrypt and set the keystore password.
     */
    public function setPassword(string $password): void
    {
        $this->encrypted_password = Crypt::encryptString($password);
    }

    /**
     * Decrypt and get the keystore password.
     */
    public function getPassword(): string
    {
        return Crypt::decryptString($this->encrypted_password);
    }

    /**
     * Encrypt and set the key password (if different from keystore password).
     */
    public function setKeyPassword(?string $password): void
    {
        if ($password) {
            $this->encrypted_key_password = Crypt::encryptString($password);
        }
    }

    /**
     * Decrypt and get the key password.
     */
    public function getKeyPassword(): ?string
    {
        if (! $this->encrypted_key_password) {
            return null;
        }

        return Crypt::decryptString($this->encrypted_key_password);
    }

    /**
     * Get the display-friendly alias.
     * Returns 'Auto-generated' if alias is null or empty.
     */
    public function getDisplayAlias(): string
    {
        return $this->alias ?? 'Auto-generated';
    }

    /**
     * Check if this keystore is a debug/auto-generated keystore.
     */
    public function isAutoGenerated(): bool
    {
        return $this->alias === 'auto-generated' || $this->alias === null;
    }

    /**
     * Get a formatted display name with alias.
     */
    public function getDisplayName(): string
    {
        return sprintf('%s (%s)', $this->name, $this->getDisplayAlias());
    }
}
