<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\MicrosoftGraphTokenManager;
use App\Services\OneDriveService;
use Carbon\Carbon;


class OneDriveController extends Controller
{
    public function __construct(
        private OneDriveService $drive,
        private MicrosoftGraphTokenManager $tokens
    ) {}

    private function ensureAccessToken(): string
    {
        $graph = session('graph');
        if (!$graph) abort(401, 'Not signed in to Microsoft.');

        $access = $graph['access_token'];
        $exp = Carbon::parse($graph['expires_at'] ?? now());
        if (now()->greaterThanOrEqualTo($exp) && !empty($graph['refresh_token'])) {
            $new = $this->tokens->refresh($graph['refresh_token']);
            $access = $new['access_token'];
            session(['graph' => [
                'access_token'  => $access,
                'refresh_token' => $new['refresh_token'] ?? $graph['refresh_token'],
                'expires_at'    => now()->addSeconds($new['expires_in'] ?? 3600)->toIso8601String(),
            ]]);
        }
        return $access;
    }

    public function tryDownload(Request $req)
    {
        $path = $req->query('path', 'Reports/PO/Latest_PO_Summary.xlsx');
        $accessToken = $this->ensureAccessToken();

        $savedPath = $this->drive->downloadByPath($accessToken, $path, basename($path));
        return response()->download($savedPath);
    }

    public function tryList(Request $req)
    {
        $folder = $req->query('folder', '');
        $accessToken = $this->ensureAccessToken();

        $items = $this->drive->listByPath($accessToken, $folder);
        return response()->json($items);
    }
}
