<?php

declare(strict_types=1);

namespace FecaMailshots\Application;

use FecaMailshots\Repository\MailCredentialRepository;
use FecaMailshots\WordPress\WordPressFacade;

final class PerUserMailCredentialsProvider implements MailCredentialsProvider
{
    private MailCredentialRepository $repo;
    private WordPressFacade $wp;

    public function __construct(MailCredentialRepository $repo, WordPressFacade $wp)
    {
        $this->repo = $repo;
        $this->wp = $wp;
    }

    public function credentials(): ?array
    {
        $uid = $this->wp->currentUserId();
        if ($uid <= 0) {
            return null;
        }

        $row = $this->repo->findByUserId($uid);
        if ($row === null) {
            return null;
        }

        foreach (['smtp_host', 'smtp_user', 'smtp_password', 'smtp_from_email'] as $required) {
            if (trim((string) ($row[$required] ?? '')) === '') {
                return null;
            }
        }

        return $row;
    }
}
