package com.qiaoba.module.tenant.init.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.http.HttpStatus;
import com.qiaoba.common.base.code.DatasourceErrorCode;
import com.qiaoba.common.database.context.TenantDbTypeContext;
import com.qiaoba.common.database.util.DbUtil;
import com.qiaoba.module.tenant.entity.vo.TenantInitVo;
import com.qiaoba.module.tenant.init.InitTablesStrategy;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 初始化表策略-Mysql
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/27 16:01
 */
@Service
public class MysqlInitTablesStrategy implements InitTablesStrategy {

    public static final String CREATE_MYSQL_DB_SQL = "CREATE DATABASE `{}` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';";

    @Override
    public TenantInitVo create(Connection conn, String schema) {

        try {
            // 创建库
            SqlExecutor.execute(conn, StrUtil.format(CREATE_MYSQL_DB_SQL, schema, schema));
        } catch (SQLException e) {
            IoUtil.close(conn);
            return new TenantInitVo(DatasourceErrorCode.CREATE_SCHEMA_ERROR.getCode(), e.getMessage());
        }

        try {
            // 切换 Schema
            DbUtil.setSchema(TenantDbTypeContext.getDefault(), conn, schema);
            DbUtil.runScript(conn, "MySQL/table/base_tables");
            return new TenantInitVo(HttpStatus.HTTP_OK, null);
        } catch (SQLException e) {
            return new TenantInitVo(DatasourceErrorCode.SWITCH_SCHEMA_ERROR.getCode(), e.getMessage());
        } catch (IOException e) {
            return new TenantInitVo(DatasourceErrorCode.CREATE_TABLE_ERROR.getCode(), e.getMessage());
        } finally {
            IoUtil.close(conn);
        }

    }

    @Override
    public TenantInitVo create(Connection conn) {
        try {
            DbUtil.runScript(conn, "MySQL/table/base_tables");
            return new TenantInitVo(HttpStatus.HTTP_OK, null);
        } catch (IOException e) {
            return new TenantInitVo(DatasourceErrorCode.CREATE_TABLE_ERROR.getCode(), e.getMessage());
        } finally {
            IoUtil.close(conn);
        }
    }
}
