<?php

namespace EasyLinkAutomations\Actions\GoogleSheets;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that deletes a sheet (tab) from a Google Spreadsheet.
 *
 * Uses the Google Sheets API v4 batchUpdate deleteSheet request.
 */
final class DeleteSheetAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'google_sheets/delete_sheet';
    }

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

    public static function getDescription(): string
    {
        return __('Delete a sheet (tab) from a 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_name' => [
                'label'         => 'Sheet',
                'type'          => 'remote_select',
                'required'      => true,
                'placeholder'   => 'Select a sheet to delete...',
                'remote_source' => 'google-sheets/sheets',
                'depends_on'    => ['connection_id', 'spreadsheet_id'],
                'options_key'   => 'sheets',
            ],
        ];
    }

    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     = (string) ($mapped['sheet_name'] ?? '');

        $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' => [
                    ['deleteSheet' => ['sheetId' => $sheetId]],
                ],
            ]
        );

        return [
            'success' => $result['success'],
            'message' => $result['success']
                ? "Sheet \"{$sheetName}\" deleted successfully"
                : 'Failed to delete sheet (HTTP ' . $result['status'] . '): ' . $result['error'],
            'data' => [
                'spreadsheet_id' => $spreadsheetId,
                'deleted_sheet'  => $sheetName,
            ],
        ];
    }
}
