<?php

namespace EasyLinkAutomations\Actions\GoogleSheets;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that adds a new sheet (tab) to an existing Google Spreadsheet.
 *
 * Uses the Google Sheets API v4 batchUpdate addSheet request.
 */
final class CreateSheetAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'google_sheets/create_sheet';
    }

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

    public static function getDescription(): string
    {
        return __('Add a new sheet (tab) to an existing 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 [
            'spreadsheet_id' => [
                'label'         => 'Spreadsheet',
                'type'          => 'remote_select',
                'required'      => true,
                'placeholder'   => 'Select a spreadsheet...',
                'remote_source' => 'google-sheets/spreadsheets',
                'depends_on'    => ['connection_id'],
                'options_key'   => 'spreadsheets',
            ],
            'sheet_title' => [
                'label'            => 'New Sheet Title',
                'type'             => 'text',
                'required'         => true,
                'placeholder'      => 'New Tab',
                'supports_mapping' => true,
            ],
            'row_count' => [
                'label'       => 'Row Count (optional)',
                'type'        => 'number',
                'required'    => false,
                'placeholder' => '1000',
                'description' => 'Number of rows in the new sheet',
            ],
            'column_count' => [
                'label'       => 'Column Count (optional)',
                'type'        => 'number',
                'required'    => false,
                'placeholder' => '26',
                'description' => 'Number of columns in the new sheet',
            ],
        ];
    }

    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);
        $spreadsheetId = $mapped['spreadsheet_id'];
        $sheetTitle    = trim((string) ($mapped['sheet_title'] ?? ''));
        if ($sheetTitle === '') {
            return ['success' => false, 'message' => 'New sheet title is required'];
        }

        $properties = ['title' => $sheetTitle];

        $gridProperties = [];
        if (!empty($mapped['row_count'])) {
            $gridProperties['rowCount'] = (int) $mapped['row_count'];
        }
        if (!empty($mapped['column_count'])) {
            $gridProperties['columnCount'] = (int) $mapped['column_count'];
        }
        if (!empty($gridProperties)) {
            $properties['gridProperties'] = $gridProperties;
        }

        $result = GoogleSheetsHelper::request(
            'POST',
            GoogleSheetsHelper::API_BASE . '/' . rawurlencode($spreadsheetId) . ':batchUpdate',
            $token,
            [
                'requests' => [
                    ['addSheet' => ['properties' => $properties]],
                ],
            ]
        );

        $createdProps = $result['body']['replies'][0]['addSheet']['properties'] ?? [];

        return [
            'success' => $result['success'],
            'message' => $result['success']
                ? "Sheet \"{$sheetTitle}\" created successfully"
                : 'Failed to create sheet (HTTP ' . $result['status'] . '): ' . $result['error'],
            'data' => [
                'spreadsheet_id' => $spreadsheetId,
                'sheet_id'       => $createdProps['sheetId'] ?? null,
                'sheet_title'    => $createdProps['title'] ?? $sheetTitle,
            ],
        ];
    }
}
