<?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);
        }
    }

    public function data(Request $request, $table)
    {
        try {
            $this->initializeDriver($request);
            
            $skip = $request->get('skip', 0);
            $take = $request->get('take', 100);
            $filters = json_decode($request->get('filters', '[]'), true);
            
            $data = $this->databaseService->getTableData($table, $take, $skip, $filters);
            
            $response = [
                'data' => $data,
            ];

            if ($request->get('requireTotalCount') === 'true') {
                $response['totalCount'] = $this->databaseService->getTableCount($table, $filters);
            }

            return Response::json($response);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }
    public function execute(Request $request)
    {
        try {
            $this->initializeDriver($request);
            $sql = $request->get('query');
            
            if (empty($sql)) {
                return Response::json(['error' => 'Query is empty'], 400);
            }

            $results = $this->databaseService->executeQuery($sql);
            
            return Response::json([
                'data' => $results,
                'count' => count($results)
            ]);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function export(Request $request)
    {
        try {
            $this->initializeDriver($request);
            $config = $request->only(['host', 'username', 'password', 'database', 'port', 'table']);
            $filters = json_decode($request->get('filters', '[]'), true);
            
            $filePath = $this->databaseService->export($config, $filters);
            
            return Response::download($filePath)->deleteFileAfterSend(true);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function import(Request $request)
    {
        try {
            if (!$request->hasFile('file')) {
                return Response::json(['error' => 'No file uploaded'], 400);
            }

            $this->initializeDriver($request);
            $config = $request->only(['host', 'username', 'password', 'database', 'port']);
            
            $file = $request->file('file');
            $tempPath = $file->storeAs('temp', $file->getClientOriginalName());
            $fullPath = storage_path('app/' . $tempPath);
            
            $this->databaseService->import($config, $fullPath);
            
            if (file_exists($fullPath)) {
                unlink($fullPath);
            }
            
            return Response::json(['message' => 'Database imported successfully']);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

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

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

    public function truncate(Request $request, $table)
    {
        try {
            $this->initializeDriver($request);
            $this->databaseService->truncateTable($table);
            return Response::json(['message' => "Table '{$table}' truncated successfully"]);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function drop(Request $request, $table)
    {
        try {
            $this->initializeDriver($request);
            $this->databaseService->dropTable($table);
            return Response::json(['message' => "Table '{$table}' dropped successfully"]);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function optimize(Request $request, $table)
    {
        try {
            $this->initializeDriver($request);
            $this->databaseService->optimizeTable($table);
            return Response::json(['message' => "Table '{$table}' optimized successfully"]);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function bulkAction(Request $request)
    {
        $request->validate([
            'tables' => 'required|array',
            'action' => 'required|string|in:truncate,drop,optimize',
            'database' => 'required|string'
        ]);

        try {
            $this->initializeDriver($request);
            $tables = $request->tables;
            $action = $request->action;
            $results = [];

            foreach ($tables as $table) {
                try {
                    switch ($action) {
                        case 'truncate':
                            $this->databaseService->truncateTable($table);
                            break;
                        case 'drop':
                            $this->databaseService->dropTable($table);
                            break;
                        case 'optimize':
                            $this->databaseService->optimizeTable($table);
                            break;
                    }
                    $results[$table] = 'success';
                } catch (\Exception $e) {
                    $results[$table] = 'error: ' . $e->getMessage();
                }
            }

            return Response::json(['message' => 'Bulk operation completed', 'results' => $results]);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

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

    public function batchUpdate(Request $request, $table)
    {
        $request->validate([
            'changes' => 'required|array',
        ]);

        try {
            $this->initializeDriver($request);
            $this->databaseService->batchUpdate($table, $request->changes);
            return Response::json(['message' => 'Batch update successful']);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }

    public function createDatabase(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:64',
            'charset' => 'nullable|string|max:32',
            'collation' => 'nullable|string|max:64',
        ]);

        try {
            $this->initializeDriver($request);
            $name = $request->get('name');
            $charset = $request->get('charset', 'utf8mb4');
            $collation = $request->get('collation', 'utf8mb4_unicode_ci');

            $this->databaseService->createDatabase($name, $charset, $collation);
            return Response::json(['message' => "Database '{$name}' created successfully"]);
        } catch (\Exception $e) {
            return Response::json(['error' => $e->getMessage()], 400);
        }
    }
}
