<?php
/**
 * Transactional permanent deletion for built-in forms.
 *
 * @package SubmissionInbox
 */

namespace SUBIN\Forms;

use SUBIN\AutoReplies\AutoReplyRuleRepository;

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- This service coordinates one transaction across plugin-owned repositories.

/**
 * Permanently removes a trashed form while preserving its historical leads.
 */
class FormPermanentDeletionService {
	/** @var FormRepository */
	private $forms;

	/** @var FormFieldRepository */
	private $fields;

	/** @var FormOrganizationRepository */
	private $organization;

	/** @var FormAnalyticsRepository */
	private $analytics;

	/** @var AutoReplyRuleRepository */
	private $auto_reply_rules;

	/**
	 * Constructor.
	 *
	 * @param FormRepository|null             $forms Form repository.
	 * @param FormFieldRepository|null        $fields Field repository.
	 * @param FormOrganizationRepository|null $organization Organization repository.
	 * @param FormAnalyticsRepository|null    $analytics Analytics repository.
	 * @param AutoReplyRuleRepository|null    $auto_reply_rules Auto-reply rule repository.
	 */
	public function __construct( $forms = null, $fields = null, $organization = null, $analytics = null, $auto_reply_rules = null ) {
		$this->forms            = $forms ?: new FormRepository();
		$this->fields           = $fields ?: new FormFieldRepository();
		$this->organization     = $organization ?: new FormOrganizationRepository();
		$this->analytics        = $analytics ?: new FormAnalyticsRepository();
		$this->auto_reply_rules = $auto_reply_rules ?: new AutoReplyRuleRepository();
	}

	/**
	 * Permanently delete one trashed form and its configuration data.
	 *
	 * Historical leads, lead fields, mail events, receipts, and notification
	 * records are intentionally preserved for auditability.
	 *
	 * @param int $form_id Form id.
	 * @return bool
	 */
	public function delete( $form_id ) {
		global $wpdb;

		$form_id = absint( $form_id );
		if ( $form_id <= 0 || false === $wpdb->query( 'START TRANSACTION' ) ) {
			return false;
		}

		try {
			$form = $this->forms->get_for_update( $form_id );
			if ( ! is_array( $form ) || FormRepository::STATUS_TRASHED !== sanitize_key( (string) ( $form['status'] ?? '' ) ) ) {
				$wpdb->query( 'ROLLBACK' );
				return false;
			}

			$cleanup_succeeded = $this->fields->delete_by_form_id( $form_id )
				&& $this->organization->delete_assignments( array( $form_id ) )
				&& $this->analytics->delete_for_forms( array( $form_id ) )
				&& $this->auto_reply_rules->delete_for_form( AutoReplyRuleRepository::PROVIDER_SUBMISSION_INBOX_FORM, (string) $form_id )
				&& $this->forms->delete_locked_row( $form_id );

			if ( ! $cleanup_succeeded || false === $wpdb->query( 'COMMIT' ) ) {
				$wpdb->query( 'ROLLBACK' );
				return false;
			}

			return true;
		} catch ( \Throwable $throwable ) {
			$wpdb->query( 'ROLLBACK' );
			return false;
		}
	}
}
