<?php

namespace EasyLinkAutomations\Actions\GoogleSheets;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that clears the values of a Google Sheet (or a specific range),
 * leaving formatting and the sheet itself intact.
 */
final class ClearSheetAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'google_sheets/clear_sheet';
    }

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

    public static function getDescription(): string
    {
        return __('Clear all values from a Google Sheet or a specific range', '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_name' => [
                'label'         => 'Sheet',
                'type'          => 'remote_select',
                'required'      => true,
                'placeholder'   => 'Select a sheet...',
                'remote_source' => 'google-sheets/sheets',
                'depends_on'    => ['connection_id', 'spreadsheet_id'],
                'options_key'   => 'sheets',
            ],
            'keep_header_row' => [
                'label'       => 'Keep Header Row',
                'type'        => 'toggle',
                'required'    => false,
                'default'     => true,
                'description' => 'Keep the first row and clear everything below it',
            ],
            'range' => [
                'label'            => 'Custom Range (optional)',
                'type'             => 'text',
                'required'         => false,
                'placeholder'      => 'A2:D100',
                'supports_mapping' => true,
                'description'      => 'Clear only this A1 range. Overrides "Keep Header Row" when set.',
            ],
        ];
    }

    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'];
        $sheetName     = $mapped['sheet_name'] ?? 'Sheet1';
        $customRange   = trim((string) ($mapped['range'] ?? ''));
        $keepHeaderRow = !empty($config['keep_header_row']);

        if ($customRange !== '') {
            // Prefix the sheet name when the user supplied only a cell range.
            $range = str_contains($customRange, '!')
                ? $customRange
                : GoogleSheetsHelper::quoteSheetName($sheetName) . '!' . $customRange;
        } elseif ($keepHeaderRow) {
            $range = GoogleSheetsHelper::quoteSheetName($sheetName) . '!A2:ZZ';
        } else {
            $range = GoogleSheetsHelper::quoteSheetName($sheetName) . '!A:ZZ';
        }

        $result = GoogleSheetsHelper::request(
            'POST',
            GoogleSheetsHelper::API_BASE . '/' . rawurlencode($spreadsheetId)
                . '/values/' . rawurlencode($range) . ':clear',
            $token
        );

        $clearedRange = $result['body']['clearedRange'] ?? $range;

        return [
            'success' => $result['success'],
            'message' => $result['success']
                ? "Cleared values in {$clearedRange}"
                : 'Failed to clear sheet (HTTP ' . $result['status'] . '): ' . $result['error'],
            'data' => [
                'spreadsheet_id' => $spreadsheetId,
                'cleared_range'  => $clearedRange,
            ],
        ];
    }
}
