<?php

namespace App\Services;

use App\Models\Folder;

class FolderService extends Service
{
    /**
     * Get all folders for tenant
     */
    public function index(): \Illuminate\Database\Eloquent\Collection
    {
        return Folder::where('tenant_id', $this->tenantId())
            ->ordered()
            ->get();
    }

    /**
     * Get active folders only
     */
    public function getActiveFolders(): \Illuminate\Database\Eloquent\Collection
    {
        return Folder::where('tenant_id', $this->tenantId())
            ->active()
            ->ordered()
            ->get();
    }

    /**
     * Get folder by ID
     */
    public function show(int $id): Folder
    {
        return Folder::where('tenant_id', $this->tenantId())->findOrFail($id);
    }

    /**
     * Create new folder
     */
    public function store(array $data): Folder
    {
        $data['tenant_id'] = $this->tenantId();
        $data['created_by'] = $this->apiUserId();

        // Auto-increment display_order if not provided
        if (! isset($data['display_order'])) {
            $maxOrder = Folder::where('tenant_id', $this->tenantId())->max('display_order') ?? 0;
            $data['display_order'] = $maxOrder + 1;
        }

        return Folder::create($data);
    }

    /**
     * Update folder
     */
    public function update(int $id, array $data): Folder
    {
        $folder = $this->show($id);
        $data['updated_by'] = $this->apiUserId();

        $folder->update($data);

        return $folder->fresh();
    }

    /**
     * Delete folder (set inactive)
     */
    public function destroy(int $id): Folder
    {
        $folder = $this->show($id);

        // Check if folder has files
        if ($folder->files()->count() > 0) {
            throw new \Exception(__('error.folder_has_files'));
        }

        $folder->update([
            'is_active' => false,
            'updated_by' => $this->apiUserId(),
        ]);

        return $folder;
    }

    /**
     * Reorder folders
     */
    public function reorder(array $orders): array
    {
        $folders = [];

        foreach ($orders as $order) {
            $folder = Folder::where('tenant_id', $this->tenantId())
                ->findOrFail($order['id']);

            $folder->update([
                'display_order' => $order['display_order'],
                'updated_by' => $this->apiUserId(),
            ]);

            $folders[] = $folder->fresh();
        }

        return $folders;
    }
}
