<?php

namespace EasyLinkAutomations\HTTP\Controllers\Actions;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Actions\Rapidmail\RapidmailRecipientHelper;
use EasyLinkAutomations\Actions\Rapidmail\RapidmailRequestHelper;
use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;

/**
 * Remote option sources for rapidmail action configuration.
 *
 * Lives in the free tier because the free subscriber action depends on it;
 * the pro actions reuse the same routes rather than duplicating them.
 */
final class RapidmailController
{
    /**
     * Recipient lists available on the account.
     */
    public function recipientlists(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');
        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $result = RapidmailRequestHelper::listPaged($connectionId, '/recipientlists');
        if (!$result['success']) {
            return Response::error($result['message']);
        }

        $lists = [];
        foreach (is_array($result['data']) ? $result['data'] : [] as $list) {
            if (!is_array($list) || !isset($list['id'])) {
                continue;
            }

            $lists[] = [
                'value' => (string) $list['id'],
                'label' => (string) ($list['name'] ?? $list['id']),
            ];
        }

        return Response::success(['recipientlists' => $lists]);
    }

    /**
     * Writable recipient fields for the mapping widget.
     *
     * rapidmail's recipient schema is fixed, so this needs no API call.
     */
    public function recipientFields(Request $request): Response
    {
        if (!(int) $request->get('connection_id')) {
            return Response::error('Connection ID is required', 400);
        }

        return Response::success(['columns' => RapidmailRecipientHelper::columns()]);
    }

    /**
     * Mailings available on the account.
     */
    public function mailings(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');
        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $result = RapidmailRequestHelper::listPaged($connectionId, '/mailings', [], 200);
        if (!$result['success']) {
            return Response::error($result['message']);
        }

        $mailings = [];
        foreach (is_array($result['data']) ? $result['data'] : [] as $mailing) {
            if (!is_array($mailing) || !isset($mailing['id'])) {
                continue;
            }

            $label = (string) ($mailing['subject'] ?? $mailing['name'] ?? $mailing['id']);
            $status = trim((string) ($mailing['status'] ?? ''));
            if ($status !== '') {
                $label .= ' (' . $status . ')';
            }

            $mailings[] = [
                'value' => (string) $mailing['id'],
                'label' => $label,
            ];
        }

        return Response::success(['mailings' => $mailings]);
    }

    /**
     * Mailing folders available on the account.
     */
    public function mailingFolders(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');
        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $result = RapidmailRequestHelper::request($connectionId, 'GET', '/mailings/folders');
        if (!$result['success']) {
            return Response::error($result['message']);
        }

        $folders = [];
        foreach (RapidmailRequestHelper::embedded($result['data']) as $folder) {
            if (!is_array($folder) || !isset($folder['id'])) {
                continue;
            }

            $folders[] = [
                'value' => (string) $folder['id'],
                'label' => (string) ($folder['name'] ?? $folder['id']),
            ];
        }

        return Response::success(['folders' => $folders]);
    }
}
