<?php

namespace App\Services\Folder;

use App\Models\File;
use App\Models\Folder;
use App\Models\NamingRule;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class FoldersService
{
    public function applyNaming(string $id, string $namingRuleId): void
    {
        $folder = Folder::query()->findOrFail($id);
        $namingRule = NamingRule::query()->findOrFail($namingRuleId);
        if ($folder->naming_rule_id == $namingRule->id) {
            return;
        }
        // 子孙均需更新
        DB::transaction(function () use ($folder, $namingRule) {
            Folder::query()
                ->where('path', 'like', $folder->path . '%')
                ->update(['naming_rule_id' => $namingRule->id]);

            File::query()
                ->join('folders', 'files.folder_id', '=', 'folders.id')
                ->where('folders.path', 'like', $folder->path . '%')
                ->update(['files.naming_rule_id' => $namingRule->id, 'naming_rules' => null]);
        });
    }

    public function getAllParentTree($folderId): Collection|array
    {
        $folder = Folder::query() ->select('id', 'name', 'parent_id', 'path')->findOrFail($folderId);
        $folderIds = explode(',', $folder->path);

        $allChildren = Folder::query()
            ->select('id', 'name', 'parent_id')
            ->whereIn('id', $folderIds ?? [])
            ->get();

        return make_tree($allChildren->toArray());
    }
}