<?php

namespace EasyLinkAutomations\Actions\GoogleSheets;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that appends a new row to a Google Sheet.
 *
 * Migrated from n8n: Google Sheets v2 (resource: sheet, operation: append)
 * Uses Google Sheets API v4 to append data to a spreadsheet.
 */
final class AppendRowAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'google_sheets/append_row';
    }

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

    public static function getDescription(): string
    {
        return __('Append a new row of data to a Google Sheet', 'easylink-automations');
    }

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

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

    /**
     * This action requires a Google Sheets connection.
     */
    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',
            ],
            'field_mappings' => [
                'label'            => 'Column Mappings',
                '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',
            ],
            'insert_data_option' => [
                'label'   => 'Insert Data Option',
                'type'    => 'select',
                'options' => [
                    ['value' => 'INSERT_ROWS', 'label' => 'Insert Rows — Insert new rows for the data'],
                    ['value' => 'OVERWRITE', 'label' => 'Overwrite — Overwrite existing data in range'],
                ],
                'default' => 'INSERT_ROWS',
            ],
        ];
    }

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

        // 2. Get API credentials from connection
        $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',
            ];
        }

        // 3. Map config values with trigger data placeholders
        $mapped = $this->mapConfig($config, $triggerData);

        // 4. Parse the field_mappings (can be object or JSON string)
        $fieldMappings = GoogleSheetsHelper::parseMappings($mapped['field_mappings'] ?? '{}');
        if (empty($fieldMappings)) {
            return [
                'success' => false,
                'message' => 'Column mappings are required',
            ];
        }

        // 5. Build the API request
        $spreadsheetId    = $mapped['spreadsheet_id'];
        $sheetName        = $mapped['sheet_name'] ?? 'Sheet1';
        $headerRow        = max(1, (int) ($mapped['header_row'] ?? 1));
        $valueInputOption = $config['value_input_option'] ?? 'USER_ENTERED';
        $insertDataOption = $config['insert_data_option'] ?? 'INSERT_ROWS';

        $headerValues = GoogleSheetsHelper::readRange(
            $token,
            $spreadsheetId,
            GoogleSheetsHelper::quoteSheetName($sheetName) . "!{$headerRow}:{$headerRow}"
        );
        $rowValues = GoogleSheetsHelper::buildRowValues($fieldMappings, $headerValues[0] ?? []);

        $range = rawurlencode(GoogleSheetsHelper::quoteSheetName($sheetName) . '!A:ZZ');
        $url   = GoogleSheetsHelper::API_BASE . '/' . rawurlencode($spreadsheetId) . "/values/{$range}:append?"
               . http_build_query([
                   'valueInputOption' => $valueInputOption,
                   'insertDataOption' => $insertDataOption,
               ]);

        $body = [
            'values' => [$rowValues],
        ];

        // 6. Make the API call
        $result = GoogleSheetsHelper::request('POST', $url, $token, $body);

        // 7. Parse response
        $updatedRange = $result['body']['updates']['updatedRange'] ?? '';
        $updatedRows  = $result['body']['updates']['updatedRows'] ?? 0;

        return [
            'success' => $result['success'],
            'message' => $result['success']
                ? "Row appended successfully ({$updatedRows} row(s) in {$updatedRange})"
                : 'Failed to append row (HTTP ' . $result['status'] . '): ' . $result['error'],
            'data' => [
                'spreadsheet_id' => $spreadsheetId,
                'updated_range'  => $updatedRange,
                'updated_rows'   => $updatedRows,
            ],
        ];
    }
}
