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

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.qiaoba.common.base.code.DatasourceErrorCode;
import com.qiaoba.common.base.enums.DataBaseEnum;
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 PgSqlInitTablesStrategy implements InitTablesStrategy {

    private static final String CREATE_PGSQL_SCHEMA_SQL = "CREATE SCHEMA \"{}\";";

    @Override
    public TenantInitVo create(Connection conn, String schema) {
        try {
            // 新建模式
            DbUtil.runSql(conn, StrUtil.format(CREATE_PGSQL_SCHEMA_SQL, schema));
            // 切换模式
            DbUtil.setSchema(DataBaseEnum.POSTGRE_SQL.getType(), conn, schema);
            // 执行SQL
            return create(conn);
        } catch (SQLException e) {
            return new TenantInitVo(DatasourceErrorCode.CREATE_SCHEMA_ERROR.getCode(), e.getMessage());
        } finally {
            IoUtil.close(conn);
        }
    }

    @Override
    public TenantInitVo create(Connection conn) {
        try {
            DbUtil.runScript(conn, "init/table/PostgreSQL/create_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);
        }
    }
}
