<?php

namespace Fotogenic_AI\Compat\Wp;

use Fotogenic_AI\PostQueryAdapter;
use Fotogenic_AI\Image_Source_Resolver;
use Fotogenic_AI\Workflow_Item_Identity;

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

/**
 * WordPress Post query adapter — posts, search by title or ID, paginated.
 */
final class Post_Query_Adapter_Wp implements PostQueryAdapter {

    private const POST_TYPE = 'post';
    private const POST_STATUSES = [ 'publish', 'draft', 'pending', 'private', 'future' ];

    public function list_posts( string $q, int $page, int $per_page ): array {
        if ( ! current_user_can( 'edit_posts' ) ) {
            return [
                'items'      => [],
                'totalItems' => 0,
                'totalPages' => 1,
            ];
        }

        $per_page = max( 1, min( 50, (int) $per_page ) );
        $page     = max( 1, (int) $page );
        $query    = trim( (string) $q );

        $args = [
            'post_type'      => self::POST_TYPE,
            'post_status'    => self::POST_STATUSES,
            'posts_per_page' => $per_page,
            'paged'          => $page,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ];

        if ( '' !== $query && ctype_digit( $query ) ) {
            $args['p'] = (int) $query;
            $args['posts_per_page'] = 1;
        } elseif ( '' !== $query ) {
            $args['s'] = $query;
        }

        $wp_query = new \WP_Query( $args );
        $posts    = $wp_query->posts ?? [];
        $items    = [];

        foreach ( $posts as $post ) {
            if ( ! $post instanceof \WP_Post ) {
                continue;
            }
            $item = $this->build_item( $post->ID );
			if ( is_array( $item ) && ! empty( $item ) ) {
                $items[] = $item;
            }
        }

        $total_items = (int) ( $wp_query->found_posts ?? 0 );
        $total_pages = $per_page > 0 ? (int) ceil( $total_items / $per_page ) : 1;
        $total_pages = max( 1, $total_pages );

        return [
            'items'      => $items,
            'totalItems' => $total_items,
            'totalPages' => $total_pages,
        ];
    }

    /** @return array|null|\WP_Error */
    public function get_post_summary( int $post_id ) {
        if ( ! current_user_can( 'edit_posts' ) ) {
            return new \WP_Error( 'forbidden', __( 'You do not have permission to access posts.', 'fotogenic-ai' ), [ 'status' => 403 ] );
        }

        $post = get_post( $post_id );
        if ( ! $post || self::POST_TYPE !== ( $post->post_type ?? '' ) ) {
            return null;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return new \WP_Error( 'forbidden', __( 'You do not have permission to access this post.', 'fotogenic-ai' ), [ 'status' => 403 ] );
        }

        return $this->build_item( $post_id );
    }

	/**
	 * Build list item shape, including the attachment ID used for immutable
	 * source-policy validation after selection.
	 *
	 * @param int $post_id Post ID.
	 * @return array{id:int,label:string,imageUrl:string,sourceAttachmentId:int,target:array,editUrl:string,bytes:int,mime:string,eligible:bool,eligibilityReason:string}|\WP_Error
	 */
	private function build_item( int $post_id ) {
        $post = get_post( $post_id );
        if ( ! $post || self::POST_TYPE !== ( $post->post_type ?? '' ) ) {
            return [];
        }

		$featured_id = (int) get_post_thumbnail_id( $post_id );
		$thumb       = $featured_id ? \Fotogenic_AI\Media_Saver::get_attachment_view_url( $featured_id, 'thumbnail' ) : '';
		$url         = $featured_id ? \Fotogenic_AI\Media_Saver::get_attachment_view_url( $featured_id, 'full' ) : '';
		$eligibility = $this->get_eligibility( $post_id, $featured_id, $thumb, $url );
		$target      = Workflow_Item_Identity::resolve_target( 'post', $post_id );
		if ( is_wp_error( $target ) ) {
			return $target;
		}
		$status_object = get_post_status_object( $post->post_status );

        return [
            'id'       => (int) $post_id,
			'label'    => \Fotogenic_AI\fotogenic_ai_plain_text_label( (string) ( $post->post_title ?? '' ) ),
			'imageUrl' => $thumb ? (string) $thumb : '',
			'sourceAttachmentId' => $featured_id,
			'target'   => $target,
            'editUrl'  => (string) admin_url( 'post.php?post=' . (int) $post_id . '&action=edit' ),
			'bytes'     => (int) $eligibility['bytes'],
			'mime'      => (string) $eligibility['mime'],
			'eligible'  => (bool) $eligibility['eligible'],
			'eligibilityReason' => (string) $eligibility['eligibilityReason'],
			'status'    => (string) $post->post_status,
			'statusLabel' => is_object( $status_object ) ? (string) $status_object->label : '',
			'author'    => (string) get_the_author_meta( 'display_name', (int) $post->post_author ),
			'authorId'  => (int) $post->post_author,
        ];
    }

	/** @return array{eligible:bool,eligibilityReason:string,bytes:int,mime:string} */
	private function get_eligibility( int $post_id, int $featured_id, string $thumb, string $url ): array {
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return $this->ineligible( __( 'You do not have permission to use this post.', 'fotogenic-ai' ) );
		}
		if ( $featured_id <= 0 ) {
			return $this->ineligible( __( 'Add a featured image to this post before generating.', 'fotogenic-ai' ) );
		}
		if ( ! current_user_can( 'upload_files' ) || ! current_user_can( 'edit_post', $featured_id ) ) {
			return $this->ineligible( __( 'You do not have permission to use this post image.', 'fotogenic-ai' ) );
		}

		$eligibility = Image_Source_Resolver::instance()->get_workflow_attachment_eligibility( $featured_id );
		if ( true === $eligibility['eligible'] && ( '' === $thumb || '' === $url ) ) {
			return $this->ineligible( __( 'A preview is unavailable for this post image. Replace it to continue.', 'fotogenic-ai' ) );
		}

		return $eligibility;
	}

	/** @return array{eligible:false,eligibilityReason:string,bytes:0,mime:string} */
	private function ineligible( string $reason ): array {
		return [
			'eligible'          => false,
			'eligibilityReason' => $reason,
			'bytes'             => 0,
			'mime'              => '',
		];
	}
}
