<?php

namespace EasyLinkAutomations\Actions\GoogleSheets;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that deletes a row from a Google Sheet.
 *
 * The row can be targeted either by an explicit row number or by matching a
 * lookup column against a value. Uses the Sheets API batchUpdate endpoint.
 */
final class DeleteRowAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'google_sheets/delete_row';
    }

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

    public static function getDescription(): string
    {
        return __('Delete a row from a Google Sheet by row number or 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 (used for lookups)',
            ],
            'row_number' => [
                'label'            => 'Row Number',
                'type'             => 'number',
                'required'         => false,
                'placeholder'      => 'e.g. 5',
                'supports_mapping' => true,
                'description'      => 'Delete this exact row. Leave empty to use a lookup instead.',
            ],
            'lookup_column' => [
                'label'         => 'Lookup Column',
                'type'          => 'remote_select',
                'required'      => false,
                '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'   => 'Used only when no Row Number is given',
            ],
            'lookup_value' => [
                'label'            => 'Lookup Value',
                'type'             => 'text',
                'required'         => false,
                'placeholder'      => '{{user_email}}',
                'supports_mapping' => true,
                'description'      => 'The value to search for in the lookup column',
            ],
        ];
    }

    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));
        $rowNumber     = (int) ($mapped['row_number'] ?? 0);
        $lookupColumn  = (string) ($mapped['lookup_column'] ?? '');
        $lookupValue   = (string) ($mapped['lookup_value'] ?? '');

        // Resolve the target row: explicit number takes priority over a lookup.
        if ($rowNumber < 1) {
            if ($lookupColumn === '' || $lookupValue === '') {
                return ['success' => false, 'message' => 'Provide a Row Number, or a Lookup Column and Lookup Value'];
            }

            $values    = GoogleSheetsHelper::readRange(
                $token,
                $spreadsheetId,
                GoogleSheetsHelper::quoteSheetName($sheetName) . '!A:ZZ'
            );
            $rowNumber = GoogleSheetsHelper::findRowNumber($values, $headerRow, $lookupColumn, $lookupValue) ?? 0;

            if ($rowNumber < 1) {
                return [
                    'success' => false,
                    'message' => "No row found where \"{$lookupColumn}\" equals \"{$lookupValue}\"",
                ];
            }
        }

        $sheetId = GoogleSheetsHelper::resolveSheetId($token, $spreadsheetId, $sheetName);
        if ($sheetId === null) {
            return ['success' => false, 'message' => "Sheet \"{$sheetName}\" was not found in the spreadsheet"];
        }

        $result = GoogleSheetsHelper::request(
            'POST',
            GoogleSheetsHelper::API_BASE . '/' . rawurlencode($spreadsheetId) . ':batchUpdate',
            $token,
            [
                'requests' => [
                    [
                        'deleteDimension' => [
                            'range' => [
                                'sheetId'    => $sheetId,
                                'dimension'  => 'ROWS',
                                'startIndex' => $rowNumber - 1,
                                'endIndex'   => $rowNumber,
                            ],
                        ],
                    ],
                ],
            ]
        );

        return [
            'success' => $result['success'],
            'message' => $result['success']
                ? "Row {$rowNumber} deleted successfully"
                : 'Failed to delete row (HTTP ' . $result['status'] . '): ' . $result['error'],
            'data' => [
                'spreadsheet_id' => $spreadsheetId,
                'deleted_row'    => $rowNumber,
            ],
        ];
    }
}
