<?php
if ( ! defined( 'ABSPATH' ) ) exit;

function scholar_sync_delete_authors($author_ids)
{

    global $wpdb;
    $table_name = SCHOLAR_SYNC_DB_AUTHORS;

    // Ensure $author_ids is always an array of positive integers.
    if (!is_array($author_ids)) {
        $author_ids = [$author_ids];
    }
    $author_ids = array_filter( array_map( 'intval', $author_ids ) );
    if ( empty( $author_ids ) ) {
        return 0;
    }

    $placeholders = implode( ',', array_fill( 0, count( $author_ids ), '%d' ) );

    // Fetch scholar_ids and separate authors with/without a Google Scholar ID.
    $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- args counted at runtime (dynamic IN list)
        "SELECT author_id, scholar_id FROM %i WHERE author_id IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- dynamic IN(): array_fill()-generated %d placeholders only; IDs int-cast and passed to prepare()
        $table_name,
        ...$author_ids
    ) );

    if ( empty( $rows ) ) {
        return 0;
    }

    $scholar_ids      = array(); // scholar_id => author_id, for authors linked to the service
    $local_author_ids = array(); // author_ids with no scholar_id (local-only)

    foreach ( $rows as $row ) {
        if ( ! empty( $row->scholar_id ) ) {
            $scholar_ids[ $row->scholar_id ] = (int) $row->author_id;
        } else {
            $local_author_ids[] = (int) $row->author_id;
        }
    }

    // If any authors are linked to the service, notify it first and validate.
    if ( ! empty( $scholar_ids ) ) {
        require_once SCHOLAR_SYNC_PLUGIN_DIR . '/includes/class-scholar-sync-remote.php';
        $remote = new ScholarSync_Remote( 'customer/remove-authors' );
        $remote->retrieve_remote_data_post( array(
            'authors' => implode( ',', array_keys( $scholar_ids ) ),
        ) );

        if ( $remote->has_error() ) {
            return 0; // Service call failed — abort, do not delete locally.
        }
        // A 200 response (no error) means the authors are no longer on the service,
        // whether removed now or already absent. Proceed with local deletion.
    }

    // Service confirmed (or no service authors) — delete locally.
    $all_ids_to_delete = array_merge( array_values( $scholar_ids ), $local_author_ids );
    $del_placeholders  = implode( ',', array_fill( 0, count( $all_ids_to_delete ), '%d' ) );

    $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- args counted at runtime (dynamic IN list)
        "DELETE FROM %i WHERE author_id IN ($del_placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- dynamic IN(): array_fill()-generated %d placeholders only; IDs int-cast and passed to prepare()
        $table_name,
        ...$all_ids_to_delete
    ) );
    $num_deleted = $wpdb->rows_affected;

    $table_articles = SCHOLAR_SYNC_DB_ARTICLES;
    $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- args counted at runtime (dynamic IN list)
        "DELETE FROM %i WHERE author_id IN ($del_placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- dynamic IN(): array_fill()-generated %d placeholders only; IDs int-cast and passed to prepare()
        $table_articles,
        ...$all_ids_to_delete
    ) );

    return $num_deleted > 0 ? $num_deleted : 0;
}
