<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Folder extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'category',
        'parent_id',
        'description',
        'is_private',
        'created_by',
        'permissions',
    ];

    protected $casts = [
        'is_private' => 'boolean',
        'permissions' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the parent folder.
     */
    public function parent()
    {
        return $this->belongsTo(Folder::class, 'parent_id');
    }

    /**
     * Get the child folders - LIMITED to prevent deep recursion
     */
    public function subfolders()
    {
        return $this->hasMany(Folder::class, 'parent_id')->limit(50);
    }

    /**
     * Get all documents in this folder.
     */
    public function documents()
    {
        return $this->hasMany(Document::class);
    }

    /**
     * Get the user who created this folder.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get users who have access to this folder.
     */
    public function sharedUsers()
    {
        return $this->belongsToMany(User::class, 'folder_shares')
                    ->withPivot('permission', 'expires_at')
                    ->withTimestamps();
    }

    /**
     * Scope a query to only include accessible folders for a user - OPTIMIZED
     */
    public function scopeAccessible($query, $userId)
    {
        // Simplified to avoid complex subqueries
        return $query->where('created_by', $userId)
              ->orWhere('is_private', false);
        // Removed orWhereHas('sharedUsers') to prevent heavy query
    }

    /**
     * Get the folder path - SAFE version with depth limit
     */
    public function getPathAttribute()
    {
        $path = [];
        $folder = $this;
        $maxDepth = 10; // Prevent infinite loops
        $depth = 0;
        
        while ($folder && $depth < $maxDepth) {
            $path[] = $folder->name;
            $folder = $folder->parent;
            $depth++;
        }
        
        return implode(' / ', array_reverse($path));
    }

    /**
     * Get the total size of all documents in this folder.
     */
    public function getTotalSizeAttribute()
    {
        return $this->documents()->sum('file_size');
    }

    /**
     * Get the formatted total size.
     */
    public function getFormattedTotalSizeAttribute()
    {
        $bytes = $this->total_size;
        
        if ($bytes == 0) return '0 B';
        
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $i = floor(log($bytes, 1024));
        
        return round($bytes / pow(1024, $i), 2) . ' ' . $units[$i];
    }

    /**
     * Check if a user has permission for this folder - OPTIMIZED
     */
    public function hasPermission($userId, $permission = 'view')
    {
        if ($this->created_by == $userId) {
            return true; // Creator has full access
        }

        if (!$this->is_private) {
            return true; // Public folder
        }

        // Simplified - check share directly without loading all
        $share = \DB::table('folder_shares')
            ->where('folder_id', $this->id)
            ->where('user_id', $userId)
            ->first();

        if (!$share) {
            return false;
        }

        if ($share->expires_at && $share->expires_at < now()) {
            return false; // Share expired
        }

        $permissionLevels = ['view' => 1, 'edit' => 2, 'manage' => 3];

        return ($permissionLevels[$share->permission] ?? 0) >= ($permissionLevels[$permission] ?? 0);
    }

    /**
     * Share folder with a user.
     */
    public function shareWith($userId, $permission = 'view', $expiresAt = null)
    {
        $this->sharedUsers()->syncWithoutDetaching([
            $userId => [
                'permission' => $permission,
                'expires_at' => $expiresAt,
            ]
        ]);
    }
}