<?php

namespace RtmMail\Actions\Handlers;

use RtmMailVendor\Dependencies\SPFLib\Decoder;
use RtmMailVendor\Dependencies\SPFLib\Exception;

/**
 * Handles SPF record checking for a given domain derived from SMTP settings.
 */
class SpfLookupAction extends AbstractActionHandler
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct('test_dns_settings', 'rtm_mail_test_dns');
    }

    /**
     * Retrieves and processes the SPF record for a domain extracted from SMTP settings.
     *
     * @return array Result of SPF check including success status and message or SPF record details.
     */
    public function handleAction(): array
    {
        $settings = get_option('rtm_mail_smtp_settings');
        if (empty($settings) || !isset($settings['smtp_settings']['other'])) {
            return ['success' => false, 'message' => 'SMTP settings are incomplete.'];
        }

        $smtp = $settings['smtp_settings']['other'];
        if (!isset($smtp['other_smtp_host'])) {
            return ['success' => false, 'message' => 'SMTP host is not set.'];
        }

        $domain = $this->extractDomainFromHost($smtp['other_smtp_host']);

        $decoder = new Decoder();
        try {
            $record = $decoder->getRecordFromDomain($domain);
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error retrieving SPF record: ' . $e->getMessage()];
        }

        if ($record === null) {
            return ['success' => false, 'message' => 'No SPF record found for ' . $domain];
        }

        return [
            'success' => true,
            'message' => 'SPF record retrieval successful.',
            'spfRecord' => $this->processSPFRecord($record)
        ];
    }

    /**
     * Extracts the domain from a given host.
     *
     * @param string $host Full hostname.
     * @return string Domain name extracted from the host.
     */
    private function extractDomainFromHost($host)
    {
        return join('.', array_slice(explode('.', $host), -2));
    }

    /**
     * Processes the SPF record into a structured format.
     *
     * @param object $record SPF record object.
     * @return array Structured representation of SPF record components.
     */
    private function processSPFRecord($record)
    {
        $spfDetails = ['terms' => [], 'mechanisms' => [], 'modifiers' => []];

        foreach ($record->getTerms() as $term) {
            $spfDetails['terms'][] = (string) $term;
        }
        foreach ($record->getMechanisms() as $mechanism) {
            $spfDetails['mechanisms'][] = (string) $mechanism;
        }
        foreach ($record->getModifiers() as $modifier) {
            $spfDetails['modifiers'][] = (string) $modifier;
        }

        return $spfDetails;
    }
}
