<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Services\SharePointService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SharePointController extends Controller
{
    public function __construct(private SharePointService $sp) {}

    /**
     * Default SharePoint browse root — just the site + its document library
     * ({site}/Shared Documents). Generic on purpose: we can't assume any client's
     * internal folder layout, so both company-settings folder fields open the
     * browser at the library root and the user navigates from there (no pasted
     * link needed).
     * GET /api/v1/sharepoint/defaults
     */
    public function defaults(): JsonResponse
    {
        $cfg  = config('services.sharepoint');
        $site = rtrim((string) ($cfg['site_url'] ?? ''), '/');
        $lib  = trim((string) ($cfg['document_library'] ?? 'Shared Documents'), '/');
        $root = ($site && $lib) ? $site . '/' . $lib : ($site ?: null);

        return response()->json([
            'root'             => $root,   // {site}/{document library} — browse from here
            'document_library' => $lib,
        ]);
    }

    public function folders(Request $request)
    {
        // Not 'url' — SharePoint folder paths legitimately contain spaces
        // ("Shared Documents", "Daily Account", company names), which the strict
        // url rule rejects. SharePointService::parseUrl handles them robustly.
        $request->validate(['url' => 'required|string']);

        try {
            $folders = $this->sp->listSubfolders($request->string('url'));
            return response()->json(['folders' => $folders]);
        } catch (\Throwable $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function createFolder(Request $request)
    {
        $validated = $request->validate([
            'url'  => 'required|string',
            'name' => 'required|string|max:255',
        ]);

        try {
            $this->sp->createFolder($validated['url'], $validated['name']);
            return response()->json(['success' => true]);
        } catch (\Throwable $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
