<?php

namespace Fotogenic_AI;

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

final class Service_Library {
    public function handle_library_list( \WP_REST_Request $request ) {
        $type = sanitize_text_field( (string) $request->get_param( 'type' ) );
        $allowed = [ 'model', 'environment' ];
        if ( ! in_array( $type, $allowed, true ) ) {
            return Messages::error( 'invalid_request', 400 );
        }
        $page = max( 1, (int) $request->get_param( 'page' ) );
        $per_page = (int) $request->get_param( 'perPage' );
        if ( $per_page <= 0 ) {
            $per_page = 12;
        }
        $per_page = max( 1, min( 48, $per_page ) );
        $cache_key = $this->get_library_cache_key( $type, $page, $per_page );
        $cached = get_transient( $cache_key );
        if ( is_array( $cached ) && isset( $cached['items'] ) && is_array( $cached['items'] ) ) {
            $has_invalid = false;
            foreach ( $cached['items'] as $item ) {
                $attachment_id = isset( $item['attachmentId'] ) ? (int) $item['attachmentId'] : 0;
                if ( $attachment_id <= 0 || 'attachment' !== get_post_type( $attachment_id ) || ! wp_attachment_is_image( $attachment_id ) ) {
                    $has_invalid = true;
                    break;
                }
            }
            if ( ! $has_invalid ) {
                return rest_ensure_response( [
                    'items'   => $cached['items'],
                    'total'   => (int) ( $cached['total'] ?? count( $cached['items'] ) ),
                    'page'    => (int) ( $cached['page'] ?? $page ),
                    'perPage' => (int) ( $cached['perPage'] ?? $per_page ),
                ] );
            }
            delete_transient( $cache_key );
        }
        // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Attachment library is intentionally filtered by a single plugin-owned meta flag.
        $query = new \WP_Query(
            [
                'post_type'      => 'attachment',
                'post_status'    => 'inherit',
                'post_mime_type' => 'image',
                'posts_per_page' => $per_page,
                'paged'          => $page,
                'orderby'        => 'date',
                'order'          => 'DESC',
                'meta_query'     => [
                    [
                        'key'   => '_fotogenic_ai_library_type',
                        'value' => $type,
                    ],
                ],
            ]
        );
        // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_query
        $items = [];
        foreach ( $query->posts as $post ) {
            $attachment_id = (int) $post->ID;
            $thumb = Media_Saver::get_attachment_view_url( $attachment_id, 'large' );
            $full = Media_Saver::get_attachment_view_url( $attachment_id, 'full' );
            $items[] = [
                'attachmentId' => $attachment_id,
				'name'         => wp_basename( (string) get_attached_file( $attachment_id ) ) ?: fotogenic_ai_plain_text_label( (string) get_the_title( $attachment_id ) ),
                'thumbUrl'     => $thumb ?: '',
                'fullUrl'      => $full ?: '',
            ];
        }
        $payload = [
            'items'   => $items,
            'total'   => (int) $query->found_posts,
            'page'    => $page,
            'perPage' => $per_page,
        ];
        set_transient( $cache_key, $payload, 12 * HOUR_IN_SECONDS );

        return rest_ensure_response( [
            'items'   => $items,
            'total'   => (int) $query->found_posts,
            'page'    => $page,
            'perPage' => $per_page,
        ] );
    }

    public function handle_library_add( \WP_REST_Request $request ) {
        $type = sanitize_text_field( (string) $request->get_param( 'type' ) );
        $allowed = [ 'model', 'environment' ];
        if ( ! in_array( $type, $allowed, true ) ) {
            return Messages::error( 'invalid_request', 400 );
        }
        $attachment_id = (int) $request->get_param( 'attachmentId' );
        if ( $attachment_id <= 0 || 'attachment' !== get_post_type( $attachment_id ) ) {
            return Messages::error( 'invalid_request', 400 );
        }
        if ( ! wp_attachment_is_image( $attachment_id ) ) {
            return Messages::error( 'invalid_request', 400 );
        }
        if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
            return Messages::error( 'forbidden_remove', 403 );
        }
        update_post_meta( $attachment_id, '_fotogenic_ai_library_type', $type );
        $this->invalidate_library_cache( $type );

        return rest_ensure_response( [ 'changed' => true ] );
    }

    public function invalidate_library_cache( ?string $type = null ): void {
        $types = $type ? [ $type ] : [ 'model', 'environment' ];
        foreach ( $types as $entry ) {
            $key = $this->get_library_cache_version_key( $entry );
            $version = $this->get_library_cache_version( $entry );
            set_transient( $key, $version + 1, DAY_IN_SECONDS );
        }
    }

    private function get_library_cache_version_key( string $type ): string {
        return 'fotogenic_ai_studio_library_version_' . $type;
    }

    private function get_library_cache_version( string $type ): int {
        $key = $this->get_library_cache_version_key( $type );
        $version = (int) get_transient( $key );
        if ( $version <= 0 ) {
            $version = 1;
            set_transient( $key, $version, DAY_IN_SECONDS );
        }
        return $version;
    }

    private function get_library_cache_key( string $type, int $page, int $per_page ): string {
        $version = $this->get_library_cache_version( $type );
        return sprintf( 'fotogenic_ai_studio_library_%s_v%d_p%d_pp%d', $type, $version, $page, $per_page );
    }
}
