<?php

namespace Modules\Authentication\Http\Controllers\API;

use Exception;
use App\Traits\Authenticatable;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;

class UtilityController extends Controller
{
    use Authenticatable;

    public function linkStorage()
    {
        $publicStorage = public_path('storage');
        $target = storage_path('app/public');

        try {
            if (! File::exists($publicStorage)) {
                File::link($target, $publicStorage);

                return response()->json(['status' => 'success', 'message' => 'Storage link created.']);
            } else {
                return response()->json(['status' => 'info', 'message' => 'Storage link already exists.']);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function unlinkStorage()
    {
        $publicStorage = public_path('storage');

        try {
            if (is_link($publicStorage)) {
                unlink($publicStorage);
            } elseif (is_dir($publicStorage)) {
                // Attempt to delete via Laravel
                if (! File::deleteDirectory($publicStorage)) {
                    // Fallback for stubborn directories
                    exec('rm -rf ' . escapeshellarg($publicStorage));
                }
            }

            return response()->json([
                'status' => 'success',
                'message' => 'The storage link or directory has been removed.',
            ]);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed: ' . $e->getMessage(),
            ]);
        }
    }

    public function clearAllCache()
    {
        try {
            Artisan::call('config:clear');
            Artisan::call('cache:clear');
            Artisan::call('route:clear');
            Artisan::call('view:clear');

            return response()->json(['status' => 'success', 'message' => 'All caches cleared.']);
        } catch (Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
}
