<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DataConnection;
use App\Services\DataConnectionService;
use App\Http\Middleware\OnlyFullVersion;
use App\Http\Requests\testDataConnectionRequest;
use App\Http\Requests\StoreDataConnectionRequest;
use App\Http\Requests\updateDataConnectionRequest;

class DataConnectionController extends Controller
{
    public $dataConnectionService;

    public function __construct(DataConnectionService $dataConnectionService)
    {
        $this->dataConnectionService = $dataConnectionService;

        $this->middleware(OnlyFullVersion::class)->only(
            [
                'store',
                'update',
                'destroy',
                'testConnection'
            ]
        );
    }

    public function index()
    {
        $default_creation_date = $this->dataConnectionService->getInstalledVersionDate();

        $connections = $this->dataConnectionService->getAllConnections();

        $databases = $this->dataConnectionService->getAllDatabases();

        $servers = $this->dataConnectionService->getAllServers();

        return view(
            'dashboard.data-connections.index',
            compact(
                'default_creation_date',
                'connections',
                'databases',
                'servers'
            )
        );
    }

    public function store(StoreDataConnectionRequest $request)
    {
        $this->dataConnectionService->store($request->validated());

        return response()->json([
            'message' => "The database connection is added successfully!"
        ]);
    }

    public function edit(DataConnection $connection)
    {
        return view('dashboard.data-connections.edit', compact('connection'));
    }


    public function update(updateDataConnectionRequest $request, DataConnection $connection)
    {
        $this->dataConnectionService->update($request->validated(), $connection);

        return response()->json([
            'message' => "Data connection is updated successfully!"
        ]);
    }

    public function destroy(DataConnection $connection)
    {
        $message = $this->dataConnectionService->destory($connection);

        return response()->json([
            'message' => $message
        ]);
    }

    public function testConnection(testDataConnectionRequest $request)
    {
        $this->dataConnectionService->testConnection($request->validated());

        return response()->json([
            'message' => "Connection success"
        ]);
    }
}
