<?php

namespace App\Services\Documents;

use App\Models\Asset;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class DocumentGeneratorService {
    public string $template;
    public array $data;
    public array $options = [];

    public array $mimes = [
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'pdf' => 'application/pdf',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];

    public static array $classes = [
        'pdf' => GeneratePdfDocument::class,
        'word' => GenerateWordDocument::class
    ];

    public static function generate(string $type, string $template, array $data, array $options = []) {
        return ($class = self::$classes[$type] ?? null) ? new $class($template, $data, $options) : null;
    }


    public function __construct(string $template, array $data, array $options = []) {
        $this->template = $template;
        $this->data = $data;
        $this->options = array_merge($this->options, $options);
    }



    public function makeFilePath($ext): string {
        $fileName = Str::lower(Str::random());
        $dir = "documents/generated/{$fileName[0]}";
        Storage::makeDirectory($dir);
        return "{$dir}/{$fileName}.{$ext}";
    }

    public function makeAsset($path, $name) {
        $info = pathinfo($path);
        return Asset::create([
            'type' => 'document',
            'path' => $path,
            'mime' => $this->mimes[$info['extension']] ?? null,
            'name' => $name ?? $info['basename'],
            'filename' => $info['basename'],
            'extension' => $info['extension'],
            'user_id' => ($user = Auth::user()) ? $user->id : null
        ]);
    }
}