<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Services\DatabaseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DatabaseController extends Controller
{
    protected DatabaseService $dbService;

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

    public function list(): JsonResponse
    {
        try {
            $tables = $this->dbService->getTables();

            foreach ($tables as &$table) {
                $table['is_system'] = $this->dbService->isSystemTable($table['Name']);
            }

            return response()->json(ApiResponse::success($tables));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '获取数据表列表失败：'.$e->getMessage()));
        }
    }

    public function structure(string $table): JsonResponse
    {
        try {
            $columns = $this->dbService->getTableColumns($table);

            return response()->json(ApiResponse::success($columns));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '获取表结构失败：'.$e->getMessage()));
        }
    }

    public function addTable(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
                'name' => 'required|string|max:200',
            ]);

            $this->dbService->createTable($request->input('table'), $request->input('name'));

            return response()->json(ApiResponse::success(null, '创建成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '创建数据表失败：'.$e->getMessage()));
        }
    }

    public function editTable(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'old_table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
                'table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
                'name' => 'required|string|max:200',
            ]);

            $this->dbService->editTable(
                $request->input('old_table'),
                $request->input('table'),
                $request->input('name')
            );

            return response()->json(ApiResponse::success(null, '修改成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '修改数据表失败：'.$e->getMessage()));
        }
    }

    public function copyTable(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'source_table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
                'new_table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
            ]);

            $this->dbService->copyTable(
                $request->input('source_table'),
                $request->input('new_table')
            );

            return response()->json(ApiResponse::success(null, '复制成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '复制数据表失败：'.$e->getMessage()));
        }
    }

    public function deleteTable(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
            ]);

            $this->dbService->deleteTable($request->input('table'));

            return response()->json(ApiResponse::success(null, '删除成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '删除数据表失败：'.$e->getMessage()));
        }
    }

    public function optimize(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
            ]);

            $result = $this->dbService->optimizeTable($request->input('table'));

            if ($result['success']) {
                return response()->json(ApiResponse::success(null, $result['message']));
            }

            return response()->json(ApiResponse::error(50001, $result['message']));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '优化失败：'.$e->getMessage()));
        }
    }

    public function repair(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'table' => 'required|string|regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
            ]);

            $result = $this->dbService->repairTable($request->input('table'));

            if ($result['success']) {
                return response()->json(ApiResponse::success(null, $result['message']));
            }

            return response()->json(ApiResponse::error(50001, $result['message']));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '修复失败：'.$e->getMessage()));
        }
    }

    public function check(string $table, Request $request): JsonResponse
    {
        try {
            $page = (int) $request->input('page', 1);
            $perPage = (int) $request->input('limit', 20);
            $searchField = $request->input('field');
            $searchValue = $request->input('keyword');

            $data = $this->dbService->getTableData($table, $page, $perPage, $searchField, $searchValue);

            return response()->json([
                'code' => 0,
                'message' => 'success',
                'data' => $data,
                'timestamp' => time(),
            ]);
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '查询数据失败：'.$e->getMessage()));
        }
    }

    public function tableAdd(string $table, Request $request): JsonResponse
    {
        try {
            $data = $request->except(['_token']);
            if (empty($data)) {
                return response()->json(ApiResponse::error(40201, '提交数据不能为空'));
            }

            $this->dbService->addTableRow($table, $data);

            return response()->json(ApiResponse::success(null, '添加成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '添加数据失败：'.$e->getMessage()));
        }
    }

    public function tableEdit(string $table, Request $request): JsonResponse
    {
        try {
            $id = $request->input('id');
            $data = $request->except(['_token', 'id']);

            if (empty($id)) {
                return response()->json(ApiResponse::error(40201, '缺少ID参数'));
            }

            if (empty($data)) {
                return response()->json(ApiResponse::error(40201, '提交数据不能为空'));
            }

            $this->dbService->editTableRow($table, (int) $id, $data);

            return response()->json(ApiResponse::success(null, '修改成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '修改数据失败：'.$e->getMessage()));
        }
    }

    public function tableDelete(string $table, Request $request): JsonResponse
    {
        try {
            $ids = $request->input('ids', []);

            if (empty($ids)) {
                $id = $request->input('id');
                if ($id) {
                    $ids = [$id];
                }
            }

            if (empty($ids)) {
                return response()->json(ApiResponse::error(40201, '请选择要删除的记录'));
            }

            $this->dbService->deleteTableRows($table, $ids);

            return response()->json(ApiResponse::success(null, '删除成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '删除数据失败：'.$e->getMessage()));
        }
    }

    public function addFields(string $table, Request $request): JsonResponse
    {
        try {
            $fields = $request->input('fields', []);
            $afterField = $request->input('after_field', '');

            if (empty($fields)) {
                return response()->json(ApiResponse::error(40201, '字段数据不能为空'));
            }

            $this->dbService->addFields($table, $fields, $afterField);

            return response()->json(ApiResponse::success(null, '添加字段成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '添加字段失败：'.$e->getMessage()));
        }
    }

    public function editField(string $table, Request $request): JsonResponse
    {
        try {
            $request->validate([
                'old_name' => 'required|string',
                'name' => 'required|string',
                'type' => 'required|string',
            ]);

            $this->dbService->editField(
                $table,
                $request->input('old_name'),
                $request->input('name'),
                $request->input('type'),
                $request->input('length'),
                $request->input('default', 'NONE'),
                $request->input('default_val', ''),
                $request->input('remark', ''),
                $request->input('after_field', '')
            );

            return response()->json(ApiResponse::success(null, '修改字段成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '修改字段失败：'.$e->getMessage()));
        }
    }

    public function deleteField(string $table, Request $request): JsonResponse
    {
        try {
            $request->validate([
                'field' => 'required|string',
            ]);

            $this->dbService->deleteField($table, $request->input('field'));

            return response()->json(ApiResponse::success(null, '删除字段成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '删除字段失败：'.$e->getMessage()));
        }
    }

    public function deleteFields(string $table, Request $request): JsonResponse
    {
        try {
            $fields = $request->input('fields', []);

            if (empty($fields)) {
                return response()->json(ApiResponse::error(40201, '请选择要删除的字段'));
            }

            $this->dbService->deleteFields($table, $fields);

            return response()->json(ApiResponse::success(null, '删除字段成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '删除字段失败：'.$e->getMessage()));
        }
    }

    public function fieldIndex(string $table, Request $request): JsonResponse
    {
        try {
            $request->validate([
                'field' => 'required|string',
            ]);

            $this->dbService->addFieldIndex($table, $request->input('field'));

            return response()->json(ApiResponse::success(null, '添加索引成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '添加索引失败：'.$e->getMessage()));
        }
    }

    public function backup(Request $request): JsonResponse
    {
        try {
            $table = $request->input('table');
            $volumeSize = (int) $request->input('volume_size', 2);
            $volumeSize = max(1, min(100, $volumeSize));

            if ($table) {
                $this->dbService->backupTable($table, $volumeSize);
            } else {
                $this->dbService->backupAll($volumeSize);
            }

            return response()->json(ApiResponse::success(null, '备份成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '备份失败：'.$e->getMessage()));
        }
    }

    public function backupList(string $table): JsonResponse
    {
        try {
            $list = $this->dbService->getBackupList($table);

            return response()->json(ApiResponse::success($list));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '获取备份列表失败：'.$e->getMessage()));
        }
    }

    public function recoverBackup(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'table' => 'required|string',
                'filename' => 'required|string',
            ]);

            $this->dbService->recoverBackup($request->input('table'), $request->input('filename'));

            return response()->json(ApiResponse::success(null, '恢复成功'));
        } catch (\Throwable $e) {
            return response()->json(ApiResponse::error(50001, '恢复失败：'.$e->getMessage()));
        }
    }

    public function deleteBackup(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'table' => 'required|string',
                'filenames' => 'required|array',
            ]);

            $this->dbService->deleteBackups($request->input('table'), $request->input('filenames'));

            return response()->json(ApiResponse::success(null, '删除备份成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '删除备份失败：'.$e->getMessage()));
        }
    }
}
