<?php

namespace EasyLinkAutomations\HTTP\Controllers\Actions;

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

use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;
use EasyLinkAutomations\Models\Connection;
use EasyLinkAutomations\Actions\Brevo\BrevoRequestHelper;

/**
 * Controller for Brevo related API calls.
 * Handles fetching contact attributes, lists, templates, and senders.
 */
final class BrevoController
{
    /**
     * Get contact attributes (custom fields) for field mapping.
     *
     * Fetches from GET /v3/contacts/attributes
     */
    public function contactAttributes(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        $url = BrevoRequestHelper::url('contacts/attributes');
        $response = wp_remote_get($url, [
            'headers' => BrevoRequestHelper::headers($token),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch attributes: ' . $response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $statusCode = wp_remote_retrieve_response_code($response);

        if ($statusCode < 200 || $statusCode >= 300) {
            return Response::error('Brevo API error: ' . BrevoRequestHelper::failureMessage($statusCode, $body), $statusCode);
        }

        $columns = [];

        // Add email as a required field (always needed for contact create/upsert)
        $columns[] = [
            'value'    => 'EMAIL',
            'label'    => 'Email',
            'required' => true,
        ];

        foreach ($body['attributes'] ?? [] as $attribute) {
            $name     = $attribute['name'] ?? '';
            $category = $attribute['category'] ?? 'normal';

            if (empty($name)) {
                continue;
            }

            // Skip calculated and global attributes — they can't be set by the user
            if ($category === 'calculated' || $category === 'global') {
                continue;
            }

            $columns[] = [
                'value' => $name,
                'label' => $name . ' (' . $category . ')',
            ];
        }

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

    /**
     * Get contact lists for multi-select input.
     *
     * Fetches from GET /v3/contacts/lists
     */
    public function lists(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        $url = BrevoRequestHelper::url('contacts/lists', [
            'limit'  => 50,
            'offset' => 0,
        ]);

        $response = wp_remote_get($url, [
            'headers' => BrevoRequestHelper::headers($token),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch lists: ' . $response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $statusCode = wp_remote_retrieve_response_code($response);

        if ($statusCode < 200 || $statusCode >= 300) {
            return Response::error('Brevo API error: ' . BrevoRequestHelper::failureMessage($statusCode, $body), $statusCode);
        }

        $lists = [];
        foreach ($body['lists'] ?? [] as $list) {
            $lists[] = [
                'value' => (string) ($list['id'] ?? ''),
                'label' => $list['name'] ?? ('List #' . ($list['id'] ?? '')),
            ];
        }

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

    /**
     * Get email templates for remote select.
     *
     * Fetches from GET /v3/smtp/templates
     */
    public function templates(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        $url = BrevoRequestHelper::url('smtp/templates', [
            'templateStatus' => 'true',
            'limit'          => 1000,
            'offset'         => 0,
            'sort'           => 'desc',
        ]);

        $response = wp_remote_get($url, [
            'headers' => BrevoRequestHelper::headers($token),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch templates: ' . $response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $statusCode = wp_remote_retrieve_response_code($response);

        if ($statusCode < 200 || $statusCode >= 300) {
            return Response::error('Brevo API error: ' . BrevoRequestHelper::failureMessage($statusCode, $body), $statusCode);
        }

        $templates = [];
        foreach ($body['templates'] ?? [] as $template) {
            $templates[] = [
                'value' => (string) ($template['id'] ?? ''),
                'label' => $template['name'] ?? ('Template #' . ($template['id'] ?? '')),
            ];
        }

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

    /**
     * Get senders for remote select.
     *
     * Fetches from GET /v3/senders
     */
    public function senders(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        $url = BrevoRequestHelper::url('senders');
        $response = wp_remote_get($url, [
            'headers' => BrevoRequestHelper::headers($token),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch senders: ' . $response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $statusCode = wp_remote_retrieve_response_code($response);

        if ($statusCode < 200 || $statusCode >= 300) {
            return Response::error('Brevo API error: ' . BrevoRequestHelper::failureMessage($statusCode, $body), $statusCode);
        }

        $senders = [];
        foreach ($body['senders'] ?? [] as $sender) {
            $email = $sender['email'] ?? '';
            $name  = $sender['name'] ?? '';
            $label = $name ? "{$name} ({$email})" : $email;

            $senders[] = [
                'value' => $email,
                'label' => $label,
            ];
        }

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

    /**
     * Get sender IDs for destructive sender operations.
     */
    public function senderIds(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        $response = wp_remote_get(BrevoRequestHelper::url('senders'), [
            'headers' => BrevoRequestHelper::headers($token),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch senders: ' . $response->get_error_message());
        }

        $body       = json_decode(wp_remote_retrieve_body($response), true);
        $statusCode = wp_remote_retrieve_response_code($response);

        if ($statusCode < 200 || $statusCode >= 300) {
            return Response::error('Brevo API error: ' . BrevoRequestHelper::failureMessage($statusCode, $body), $statusCode);
        }

        $senders = [];
        foreach ($body['senders'] ?? [] as $sender) {
            $id    = $sender['id'] ?? null;
            $email = $sender['email'] ?? '';
            $name  = $sender['name'] ?? '';

            if ($id === null) {
                continue;
            }

            $senders[] = [
                'value' => (string) $id,
                'label' => trim(($name ? $name . ' ' : '') . ($email ? '(' . $email . ')' : 'Sender #' . $id)),
            ];
        }

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