<?php

namespace Fotogenic_AI;

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

final class Rest {
    private static ?Rest $instance = null;
    private ?Rest_Router $router = null;
    private Service_History $history_service;
    private Service_Library $library_service;

    private function __construct() {
        // All plugin PHP files are loaded via includes/load.php (required from main plugin file).
    }

    public static function instance(): Rest {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function init(): void {
        add_action( 'rest_api_init', [ $this, 'register_routes' ] );
        add_action( 'delete_attachment', [ $this, 'handle_delete_attachment' ], 10, 1 );
        add_action( 'trashed_post', [ $this, 'handle_attachment_trashed' ] );
        add_action( 'deleted_post', [ $this, 'handle_attachment_trashed' ] );
    }

    public function handle_delete_attachment( int $post_id ): void {
        if ( 'attachment' !== get_post_type( $post_id ) ) {
            return;
        }
        Bulk_Repo::instance()->clear_attachment_references( $post_id );
        $product_id = (int) get_post_meta( $post_id, '_fotogenic_ai_source_product_id', true );
        if ( $product_id > 0 ) {
            Studio_Cache_Store::flush_all_caches();
        }
    }

    public function handle_attachment_trashed( int $post_id ): void {
        if ( 'attachment' !== get_post_type( $post_id ) ) {
            return;
        }
        $this->ensure_services();
        Bulk_Repo::instance()->clear_attachment_references( $post_id );
        $type = (string) get_post_meta( $post_id, '_fotogenic_ai_library_type', true );
        if ( '' === $type ) {
            $product_id = (int) get_post_meta( $post_id, '_fotogenic_ai_source_product_id', true );
            if ( $product_id > 0 ) {
                Studio_Cache_Store::flush_all_caches();
            }
            return;
        }
        if ( in_array( $type, [ 'model', 'inspiration', 'environment' ], true ) ) {
            $this->library_service->invalidate_library_cache( $type );
        }
        $product_id = (int) get_post_meta( $post_id, '_fotogenic_ai_source_product_id', true );
        if ( $product_id > 0 ) {
            Studio_Cache_Store::flush_all_caches();
        }
    }

    public function register_routes(): void {
        $this->ensure_router();
        $this->router->register_routes();
    }

    private function ensure_services(): void {
        if ( isset( $this->history_service ) && isset( $this->library_service ) ) {
            return;
        }
        $this->history_service = new Service_History();
        $this->library_service = new Service_Library();
    }

    private function ensure_router(): void {
        if ( null !== $this->router ) {
            return;
        }
        $compat                      = Plugin::instance()->compat();
        $product_query_adapter       = $compat->get_product_query_adapter();
        $product_media_write_adapter = $compat->get_product_media_write_adapter();

        $this->ensure_services();
        $generate_poll_service = new Service_Generate_Poll();
        $generate_active_service = new Service_Generate_Active();
        $generate_save_service = new Service_Generate_Save( $product_media_write_adapter );
        $generate_remove_service = new Service_Generate_Remove( $product_media_write_adapter );
        $configuration_service = new Service_Configuration();
        $credits_service = new Service_Credits();
        $experiences_service = new Service_Experiences();
        $bulk_service = new Service_Bulk();
		$store_queue_service = new Service_Store_Queue();

        $media_query_adapter         = $compat->get_media_query_adapter();
        $post_query_adapter          = $compat->get_post_query_adapter();
        $page_query_adapter          = $compat->get_page_query_adapter();

        $this->router = Rest_Router::instance( [
            new Rest_Studio_Run( $generate_active_service, $generate_poll_service ),
            new Rest_Studio_Results( $generate_save_service, $generate_remove_service ),
            new Rest_Configuration( $configuration_service ),
            new Rest_Credits( $credits_service ),
            new Rest_Experiences( $experiences_service ),
            new Rest_Auth(),
            new Rest_Library( $this->library_service ),
            new Rest_History( $this->history_service ),
            new Rest_Admin(),
            new Rest_Studio_Bulk( $bulk_service ),
			new Rest_Studio_Store_Queue( $store_queue_service ),
            new Rest_Studio( $product_query_adapter ),
            new Rest_Studio_Media( $media_query_adapter ),
            new Rest_Studio_Post( $post_query_adapter ),
            new Rest_Studio_Page( $page_query_adapter ),
            new Rest_Universal_Studio(),
        ] );
    }
}
