<?php

namespace EasyLinkAutomations\Actions\GoogleSheets;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that creates a brand-new Google Spreadsheet.
 *
 * Uses the Google Sheets API v4 spreadsheets.create endpoint.
 */
final class CreateSpreadsheetAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'google_sheets/create_spreadsheet';
    }

    public static function getName(): string
    {
        return __('Create Spreadsheet', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Create a new Google Spreadsheet', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'Google Sheets';
    }

    public static function getIcon(): string
    {
        return 'google-sheets';
    }

    public static function getRequiresConnection(): ?string
    {
        return 'google_sheets';
    }

    public static function getConfigFields(): array
    {
        return [
            'title' => [
                'label'            => 'Spreadsheet Title',
                'type'             => 'text',
                'required'         => true,
                'placeholder'      => 'My New Spreadsheet',
                'supports_mapping' => true,
            ],
            'sheet_titles' => [
                'label'            => 'Sheet Tabs (optional)',
                'type'             => 'text',
                'required'         => false,
                'placeholder'      => 'Sheet1, Sheet2, Archive',
                'supports_mapping' => true,
                'description'      => 'Comma-separated tab names. Leave empty for a single default sheet.',
            ],
            'locale' => [
                'label'       => 'Locale (optional)',
                'type'        => 'text',
                'required'    => false,
                'placeholder' => 'en_US',
                'description' => 'Spreadsheet locale, e.g. en_US',
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $missing = $this->validateRequired($config);
        if ($missing) {
            return ['success' => false, 'message' => 'Missing required fields: ' . implode(', ', $missing)];
        }

        $connectionId = (int) ($config['connection_id'] ?? 0);
        $token        = GoogleSheetsHelper::getToken($connectionId);
        if (empty($token)) {
            return ['success' => false, 'message' => 'No valid Google connection found or token expired'];
        }

        $mapped = $this->mapConfig($config, $triggerData);
        $title  = trim((string) ($mapped['title'] ?? ''));
        if ($title === '') {
            return ['success' => false, 'message' => 'Spreadsheet title is required'];
        }

        $properties = ['title' => $title];
        if (!empty($mapped['locale'])) {
            $properties['locale'] = trim((string) $mapped['locale']);
        }

        $body = ['properties' => $properties];

        $sheetTitles = array_filter(array_map('trim', explode(',', (string) ($mapped['sheet_titles'] ?? ''))));
        if (!empty($sheetTitles)) {
            $body['sheets'] = array_map(
                static fn(string $name): array => ['properties' => ['title' => $name]],
                array_values($sheetTitles)
            );
        }

        $result = GoogleSheetsHelper::request('POST', GoogleSheetsHelper::API_BASE, $token, $body);

        $spreadsheetId  = $result['body']['spreadsheetId'] ?? '';
        $spreadsheetUrl = $result['body']['spreadsheetUrl'] ?? '';

        return [
            'success' => $result['success'],
            'message' => $result['success']
                ? "Spreadsheet \"{$title}\" created successfully"
                : 'Failed to create spreadsheet (HTTP ' . $result['status'] . '): ' . $result['error'],
            'data' => [
                'spreadsheet_id'  => $spreadsheetId,
                'spreadsheet_url' => $spreadsheetUrl,
                'title'           => $title,
            ],
        ];
    }
}
