<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\DatabaseService;
use App\Services\Database\MySqlDriver;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class SchemaController extends Controller
{
    protected DatabaseService $databaseService;

    public function __construct(DatabaseService $databaseService)
    {
        $this->databaseService = $databaseService;
    }

    protected function initializeDriver(Request $request)
    {
        // In a real app, these would come from encrypted session or token
        $config = $request->only(['host', 'username', 'password', 'database', 'port']);
        $driver = new MySqlDriver();
        
        if (!$driver->connect($config)) {
            throw new \Exception("Could not connect to database.");
        }

        $this->databaseService->setDriver($driver);
    }

    public function databases(Request $request)
    {
        try {
            $this->initializeDriver($request);
            return Response::json($this->databaseService->getDatabases());
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function tables(Request $request, $database)
    {
        try {
            $request->merge(['database' => $database]);
            $this->initializeDriver($request);
            return Response::json($this->databaseService->getTables());
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function schema(Request $request, $table)
    {
        try {
            $this->initializeDriver($request);
            return Response::json($this->databaseService->getTableSchema($table));
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }
}
