<?php
/**
 * Thumbnail business logic — pure functions, no AJAX / nonce / response concerns.
 *
 * @package CoffeeWP_Media_Cleanup
 */

namespace CWPM\Service;

use CWPM\Core\Db;
use CWPM\Core\Logger;
use CWPM\Core\Trash;

defined( 'ABSPATH' ) || exit;

class ThumbnailService {

	/**
	 * Move orphan thumbnail sizes for a batch of attachment/size pairs to the trash.
	 *
	 * @param array $items Array of { id: int, sizes: string[] } maps.
	 * @return array{results:array,succeeded:int,failed:int}
	 */
	public static function delete_orphan_thumbnails( $items ) {
		$results = array();

		foreach ( $items as $item ) {
			$attach_id  = absint( $item['id'] ?? 0 );
			$size_names = isset( $item['sizes'] ) && is_array( $item['sizes'] ) ? $item['sizes'] : array();

			if ( ! $attach_id || empty( $size_names ) ) {
				continue;
			}

			$meta          = wp_get_attachment_metadata( $attach_id );
			$attached_file = get_attached_file( $attach_id );

			if ( ! $attached_file || ! is_array( $meta ) ) {
				foreach ( $size_names as $size_name ) {
					$results[] = array(
						'id'      => $attach_id,
						'size'    => sanitize_key( $size_name ),
						'success' => false,
						'error'   => 'Attachment metadata not found',
					);
				}
				continue;
			}

			$file_dir = dirname( $attached_file );
			$rel_path = get_post_meta( $attach_id, '_wp_attached_file', true );
			$rel_dir  = dirname( $rel_path );
			if ( '.' === $rel_dir ) {
				$rel_dir = '';
			}

			foreach ( $size_names as $size_name ) {
				$size_name = sanitize_key( $size_name );

				if ( empty( $meta['sizes'][ $size_name ]['file'] ) ) {
					$results[] = array(
						'id'      => $attach_id,
						'size'    => $size_name,
						'success' => true,
					);
					continue;
				}

				$thumb_path = $file_dir . '/' . $meta['sizes'][ $size_name ]['file'];

				if ( ! file_exists( $thumb_path ) ) {
					$results[] = array(
						'id'      => $attach_id,
						'size'    => $size_name,
						'success' => true,
					);
					continue;
				}

				$moved      = Trash::move_to_trash( $thumb_path, $rel_dir );
				$thumb_file = $meta['sizes'][ $size_name ]['file'] ?? $size_name;
				$thumb_size = file_exists( $thumb_path ) ? (int) filesize( $thumb_path ) : 0;
				$results[]  = array(
					'id'      => $attach_id,
					'size'    => $size_name,
					'file'    => $thumb_file,
					'bytes'   => $thumb_size,
					'success' => $moved,
				);
			}

			if ( $rel_path ) {
				Db::update_result_action( $rel_path, 'delete-orphan-thumbnails', 'orphans_cleaned' );
			}
		}

		$succeeded = count(
			array_filter(
				$results,
				function ( $r ) {
					return $r['success'];
				}
			)
		);

		$trashed_details = array();
		foreach ( $results as $r ) {
			if ( $r['success'] && ! empty( $r['file'] ) ) {
				$size_str          = $r['bytes'] > 0 ? size_format( $r['bytes'], 1 ) : '';
				$trashed_details[] = $r['file'] . ( $size_str ? ' (' . $size_str . ')' : '' );
			}
		}
		$detail = ! empty( $trashed_details ) ? ' [' . implode( '; ', $trashed_details ) . ']' : '';
		Logger::info( 'Orphan thumbnails trashed: ' . $succeeded . ' size(s).' . $detail );

		return array(
			'results'   => $results,
			'succeeded' => $succeeded,
			'failed'    => count( $results ) - $succeeded,
		);
	}
}
