<?php

namespace App\Auth;

use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;

class EloquentSessionRepository implements SessionRepository
{
    public function __construct(private UserRepository $userRepo) {}

    public function create(CreateSessionDto $dto): Session
    {
        SessionModel::create([
            'token' => $dto->token,
            'user_id' => $dto->user->getId(),
            'created_at' => $dto->createdAt,
            'expires_at' => $dto->expiresAt,
        ]);

        return new Session(
            token: $dto->token,
            user: $dto->user,
            createdAt: $dto->createdAt,
            expiresAt: $dto->expiresAt,
        );
    }

    public function findByToken(string $token): ?Session
    {
        $model = SessionModel::find($token);
        if ($model === null) {
            return null;
        }
        $user = $this->userRepo->find($model->user_id);
        if ($user === null) {
            return null;
        }
        $utc = new DateTimeZone('UTC');

        return new Session(
            token: $model->token,
            user: $user,
            createdAt: new DateTimeImmutable(
                $model->created_at->toDateTimeString(),
                $utc
            ),
            expiresAt: new DateTimeImmutable(
                $model->expires_at->toDateTimeString(),
                $utc
            ),
        );
    }

    public function deleteByToken(string $token): void
    {
        SessionModel::where('token', $token)->delete();
    }
}
