<?php

namespace App\User;

use App\Shared\ValueObject\EmailAddress;

class EloquentUserRepository implements UserRepository
{
    public function create(CreateUserDto $dto): User
    {
        $model = UserModel::create([
            'email' => $dto->email->value(),
            'password_hash' => $dto->passwordHash,
        ]);

        return $this->toDomain($model);
    }

    public function findByEmail(EmailAddress $email): ?User
    {
        $model = UserModel::where('email', $email->value())->first();

        return $model === null ? null : $this->toDomain($model);
    }

    public function findByEmailDomain(string $domain): array
    {
        $models = UserModel::where('email', 'like', '%@'.$domain)->get();
        $users = [];
        foreach ($models as $model) {
            $users[] = $this->toDomain($model);
        }

        return $users;
    }

    public function find(int $id): ?User
    {
        $model = UserModel::find($id);

        return $model === null ? null : $this->toDomain($model);
    }

    private function toDomain(UserModel $model): User
    {
        return new User(
            id: $model->id,
            email: new EmailAddress($model->email),
            passwordHash: $model->password_hash,
        );
    }
}
