<?php

namespace EasyLinkAutomations\Actions\GoogleSheets;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that updates an existing row in a Google Sheet.
 *
 * The row is located by matching a lookup column against a value, then the
 * mapped columns are written using the Google Sheets API v4.
 */
final class UpdateRowAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'google_sheets/update_row';
    }

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

    public static function getDescription(): string
    {
        return __('Update an existing row in a Google Sheet, found by matching a column value', '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',
            ],
            'header_row' => [
                'label'       => 'Header Row',
                'type'        => 'number',
                'default'     => 1,
                'required'    => false,
                'placeholder' => '1',
                'description' => 'Row number containing column headers',
            ],
            'lookup_column' => [
                'label'         => 'Lookup Column',
                'type'          => 'remote_select',
                'required'      => true,
                'placeholder'   => 'Select a column to match on...',
                'remote_source' => 'google-sheets/columns',
                'depends_on'    => ['connection_id', 'spreadsheet_id', 'sheet_name', 'header_row'],
                'options_key'   => 'columns',
                'description'   => 'The column used to find the row to update',
            ],
            'lookup_value' => [
                'label'            => 'Lookup Value',
                'type'             => 'text',
                'required'         => true,
                'placeholder'      => '{{user_email}}',
                'supports_mapping' => true,
                'description'      => 'The value to search for in the lookup column',
            ],
            'field_mappings' => [
                'label'            => 'Columns to Update',
                'type'             => 'field_mapping',
                'required'         => true,
                'remote_source'    => 'google-sheets/columns',
                'depends_on'       => ['connection_id', 'spreadsheet_id', 'sheet_name', 'header_row'],
                'options_key'      => 'columns',
                'supports_mapping' => true,
            ],
            'value_input_option' => [
                'label'   => 'Value Input Option',
                'type'    => 'select',
                'options' => [
                    ['value' => 'RAW', 'label' => 'Raw — Values are stored as-is'],
                    ['value' => 'USER_ENTERED', 'label' => 'User Entered — Parsed as if typed into the UI'],
                ],
                'default' => 'USER_ENTERED',
            ],
        ];
    }

    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';
        $headerRow        = max(1, (int) ($mapped['header_row'] ?? 1));
        $lookupColumn     = (string) ($mapped['lookup_column'] ?? '');
        $lookupValue      = (string) ($mapped['lookup_value'] ?? '');
        $valueInputOption = $config['value_input_option'] ?? 'USER_ENTERED';

        $fieldMappings = GoogleSheetsHelper::parseMappings($mapped['field_mappings'] ?? '{}');
        if (empty($fieldMappings)) {
            return ['success' => false, 'message' => 'Column mappings are required'];
        }

        $range  = GoogleSheetsHelper::quoteSheetName($sheetName) . '!A:ZZ';
        $values = GoogleSheetsHelper::readRange($token, $spreadsheetId, $range);
        if (empty($values)) {
            return ['success' => false, 'message' => 'Could not read the sheet or it is empty'];
        }

        $headers   = $values[$headerRow - 1] ?? [];
        $rowNumber = GoogleSheetsHelper::findRowNumber($values, $headerRow, $lookupColumn, $lookupValue);
        if ($rowNumber === null) {
            return [
                'success' => false,
                'message' => "No row found where \"{$lookupColumn}\" equals \"{$lookupValue}\"",
            ];
        }

        // Build one cell update per mapped column that exists in the header row.
        $data = [];
        foreach ($fieldMappings as $header => $value) {
            $columnIndex = array_search($header, $headers, true);
            if ($columnIndex === false) {
                continue;
            }
            $letter = GoogleSheetsHelper::numberToColumn((int) $columnIndex);
            $data[] = [
                'range'  => GoogleSheetsHelper::quoteSheetName($sheetName) . "!{$letter}{$rowNumber}",
                'values' => [[$value]],
            ];
        }

        if (empty($data)) {
            return ['success' => false, 'message' => 'None of the mapped columns were found in the header row'];
        }

        $result = GoogleSheetsHelper::request(
            'POST',
            GoogleSheetsHelper::API_BASE . '/' . rawurlencode($spreadsheetId) . '/values:batchUpdate',
            $token,
            [
                'valueInputOption' => $valueInputOption,
                'data'             => $data,
            ]
        );

        $updatedCells = $result['body']['totalUpdatedCells'] ?? 0;

        return [
            'success' => $result['success'],
            'message' => $result['success']
                ? "Row {$rowNumber} updated successfully ({$updatedCells} cell(s))"
                : 'Failed to update row (HTTP ' . $result['status'] . '): ' . $result['error'],
            'data' => [
                'spreadsheet_id' => $spreadsheetId,
                'row_number'     => $rowNumber,
                'updated_cells'  => $updatedCells,
            ],
        ];
    }
}
