<?php
namespace R2_Offload\Migration;

use R2_Offload\DB;
use R2_Offload\Logger;
use R2_Offload\Media\Path_Resolver;
use R2_Offload\Settings;
use R2_Offload\Storage\Storage_Client;

defined( 'ABSPATH' ) || exit;

final class Verifier {

	private Storage_Client $storage;
	private Settings $settings;
	private Logger $logger;

	public function __construct( Storage_Client $storage, Settings $settings, Logger $logger ) {
		$this->storage  = $storage;
		$this->settings = $settings;
		$this->logger   = $logger;
	}

	public function verify_attachment( int $attachment_id ): array {
		$paths = Path_Resolver::attachment_files( $attachment_id );
		if ( empty( $paths ) ) {
			return [ 'ok' => false, 'message' => 'No local files.' ];
		}

		$uploads = wp_get_upload_dir();
		$base    = trailingslashit( $uploads['basedir'] );
		$item    = DB::get_item( $attachment_id );
		$prefix  = $item && $item->object_prefix !== '' ? trim( (string) $item->object_prefix, '/' ) : $this->settings->effective_prefix();
		$missing = [];
		$mismatched = [];

		foreach ( $paths as $local ) {
			$relative   = ltrim( str_replace( $base, '', $local ), '/' );
			$object_key = $prefix !== '' ? $prefix . '/' . $relative : $relative;
			$info       = $this->storage->head_object( $object_key );
			if ( ! $info ) {
				$missing[] = $object_key;
				continue;
			}
			$local_size = (int) @filesize( $local );
			if ( $local_size > 0 && isset( $info['size'] ) && (int) $info['size'] !== $local_size ) {
				$mismatched[] = $object_key;
			}
		}

		$ok = empty( $missing ) && empty( $mismatched );
		if ( ! $ok ) {
			DB::set_status( $attachment_id, 'failed', 'Verify failed: ' . wp_json_encode( compact( 'missing', 'mismatched' ) ) );
		}
		return [
			'ok'         => $ok,
			'missing'    => $missing,
			'mismatched' => $mismatched,
		];
	}
}
