<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
<?php

declare(strict_types=1);

namespace Automattic\WooCommerce\Api\Mutations\Coupons;

use Automattic\WooCommerce\Api\ApiException;
use Automattic\WooCommerce\Api\Attributes\Description;
use Automattic\WooCommerce\Api\Attributes\RequiredCapability;
use Automattic\WooCommerce\Api\Types\Coupons\DeleteCouponResult;

/**
 * Mutation to delete a coupon.
 */
#[Description( 'Delete a coupon.' )]
#[RequiredCapability( 'manage_woocommerce' )]
class DeleteCoupon {
	/**
	 * Execute the mutation.
	 *
	 * @param int  $id    The coupon ID.
	 * @param bool $force Whether to permanently delete.
	 * @return DeleteCouponResult
	 * @throws ApiException When the coupon is not found.
	 */
	public function execute(
		#[Description( 'The ID of the coupon to delete.' )]
		int $id,
		#[Description( 'Whether to permanently delete the coupon (bypass trash).' )]
		bool $force = false,
	): DeleteCouponResult {
		$wc_coupon = new \WC_Coupon( $id );

		if ( ! $wc_coupon->get_id() ) {
			throw new ApiException( 'Coupon not found.', 'NOT_FOUND', status_code: 404 );
		}

		// Capture the raw return value. A `(bool)` cast would coerce
		// filter-originated `WP_Error` objects to `true`, reporting failure
		// as success; we need to detect that case explicitly and surface
		// the underlying error instead.
		$deleted = $wc_coupon->delete( $force );

		// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Not HTML; serialized as JSON.
		if ( $deleted instanceof \WP_Error ) {
			throw new ApiException(
				$deleted->get_error_message(),
				'INTERNAL_ERROR',
				status_code: 500,
			);
		}
		// phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped

		$result          = new DeleteCouponResult();
		$result->id      = $id;
		$result->deleted = true === $deleted;

		return $result;
	}
}
