<?php

declare(strict_types=1);

namespace App\Domain\Database\Models;

use App\Domain\Account\Models\Account;
use App\Domain\Database\Enums\DatabaseStatus;
use Database\Factories\MysqlUserFactory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property int $id
 * @property int $account_id
 * @property string $name
 * @property string $real_user_name
 * @property string $host
 * @property string $auth_plugin
 * @property DatabaseStatus $status
 * @property-read Account $account
 * @property-read Collection<int, MysqlDatabase> $databases
 */
class MysqlUser extends Model
{
    /** @use HasFactory<MysqlUserFactory> */
    use HasFactory, SoftDeletes;

    protected $table = 'mysql_users';

    protected $fillable = [
        'account_id', 'name', 'real_user_name', 'host', 'auth_plugin',
        'status', 'last_error', 'last_provisioned_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => DatabaseStatus::class,
            'last_provisioned_at' => 'datetime',
        ];
    }

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

    public function databases(): BelongsToMany
    {
        return $this->belongsToMany(MysqlDatabase::class, 'mysql_grants', 'user_id', 'database_id')
            ->withPivot('privileges')
            ->withTimestamps();
    }

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