<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class PushDocumentToPaperless implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $localPath;
    protected $fileName;
    protected $relatedEntity; // E.g., The Client or MNO Model
    protected $documentType;  // E.g., The DocumentType Model
    protected $notes;

    public function __construct($localPath, $fileName, $relatedEntity, $documentType, $notes = null)
    {
        $this->localPath = $localPath;
        $this->fileName = $fileName;
        $this->relatedEntity = $relatedEntity;
        $this->documentType = $documentType;
        $this->notes = $notes;
    }

    public function handle()
    {
        $fileContents = Storage::disk('local')->get($this->localPath);
        
        // 1. Build the multipart payload mapping
        $payload = [
            ['name' => 'title', 'contents' => $this->fileName],
        ];

        // 2. Map the Correspondent (Entity)
        if ($this->relatedEntity && $this->relatedEntity->paperless_correspondent_id) {
            $payload[] = [
                'name' => 'correspondent', 
                'contents' => $this->relatedEntity->paperless_correspondent_id
            ];
        }

        // 3. Map the Tag (Document Type)
        if ($this->documentType && $this->documentType->paperless_tag_id) {
            // Paperless expects an array of tag IDs, even if it's just one
            $payload[] = [
                'name' => 'tags', 
                'contents' => $this->documentType->paperless_tag_id
            ];
        }

        // 4. Send to Paperless
        $response = Http::withToken(env('PAPERLESS_API_TOKEN'))
            ->attach('document', $fileContents, $this->fileName)
            // Http::send allows us to pass a complex multipart array
            ->send('POST', env('PAPERLESS_URL') . '/api/documents/post_document/', [
                'multipart' => $payload
            ]);

        if (!$response->successful()) {
            Log::error('Paperless Upload Failed: ' . $response->body());
            // Optionally, release the job back to the queue to try again later
            $this->release(60); 
        }
    }
}