<?php

namespace Spatie\Mailcoach\Domain\Audience\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\Storage;
use Spatie\Mailcoach\Domain\Audience\Enums\SubscriberExportStatus;
use Spatie\Mailcoach\Domain\Audience\Models\SubscriberExport;
use Spatie\Mailcoach\Domain\Shared\Traits\UsesMailcoachModels;

class CompleteSubscribersExportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use UsesMailcoachModels;

    public function __construct(
        private SubscriberExport $subscriberExport,
        private string $path,
    ) {}

    public function handle(): void
    {
        config()->set('media-library.max_file_size', 1024 * 1024 * 1024); // 1GB

        $this->subscriberExport
            ->addMediaFromDisk($this->path, config('mailcoach.tmp_disk'))
            ->toMediaCollection('file', config('mailcoach.export_disk'));

        $this->subscriberExport->update(['status' => SubscriberExportStatus::Completed]);

        Storage::disk(config('mailcoach.tmp_disk'))->delete($this->path);
    }
}
