<?php

namespace HelpGent\App\BackgroundServices;

defined( 'ABSPATH' ) || exit;

use Exception;
use HelpGent\App\BackgroundProcessors\BackgroundProcessor;
use HelpGent\App\EnumeratedList\AttachmentTransferQueueType;
use HelpGent\App\Models\AttachmentTransferQueue as AttachmentTransferQueueModel;
use HelpGent\App\Models\AttachmentUploadSession as AttachmentUploadSessionModel;
use HelpGent\App\Repositories\AttachmentTransferQueueRepository;
use HelpGent\App\Repositories\AttachmentUploadSessionRepository;

class MediaCleanUpService extends BackgroundService {
    public function boot(): void {
        $this->background_processor = new BackgroundProcessor( 'media_clean_up' );

        $this->add_service_task( 'clean_up_media' );
    }

    public static function clean_up_media(): bool {
        /**
         * @var AttachmentTransferQueueRepository $transfer_queue_repository
         */
        $transfer_queue_repository = helpgent_singleton( AttachmentTransferQueueRepository::class );

        // Queues
        $queues = AttachmentTransferQueueModel::query( 'queue' )
            ->select( 
                [ 
                    'queue.id as queue_id', 
                    'session.id as session_id', 
                    'session.title', 
                    'session.last_sent_bytes',
                ] 
            )
            ->join( AttachmentUploadSessionModel::get_table_name() . " as session", 'session.id', 'queue.upload_id' )
            ->where( 'queue.type', AttachmentTransferQueueType::CANCELLED )
            ->pagination( 1, 10 );
        
        if ( empty( $queues ) ) {
            return false;
        }

        /**
         * @var AttachmentUploadSessionRepository $upload_session_repository
         */
        $upload_session_repository = helpgent_singleton( AttachmentUploadSessionRepository::class );

        foreach ( $queues as $queue_data ) {
            try {
                if ( absint( $queue_data->last_sent_bytes ) > 1 ) {
                    $title    = preg_replace( '/\..+$/',  '', $queue_data->title );
                    $file_src = helpgent_upload_dir( $title );

                    if ( file_exists( $file_src ) ) {
                        wp_delete_file( $file_src );
                    }
                }

                $upload_session_repository->delete( $queue_data->session_id );
                $transfer_queue_repository->delete( $queue_data->queue_id );
            } catch ( Exception $e ) {

            }
        }

        return true;
    }

    public function run(): void {
        parent::run();
        $this->set_expiration();
    }

    public function set_expiration(): void {
        $expiration = apply_filters( 'helpgent_media_clean_up_processor_execution_expiration', MINUTE_IN_SECONDS * 30 );
        set_transient( 'helpgent_executed_media_clean_up_processor', true, $expiration );
    }

    public function is_expired(): bool {
        return empty( get_transient( 'helpgent_executed_media_clean_up_processor' ) );
    }
}