package com.erp.provisioning;

import com.erp.tenant.TenantDbSettings;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 테넌트 DB 의 user_info 를 조회해서 회사 구성원 리스트를 반환.
 * 회사 관리 화면의 "구성원" 탭 전용.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CompanyMembersService {

    private final TenantDbSettings settings;

    public List<Map<String, Object>> listMembers(String dbName) {
        List<Map<String, Object>> out = new ArrayList<>();
        try (Connection c = DriverManager.getConnection(
                settings.buildJdbcUrl(dbName), settings.username(), settings.password());
             PreparedStatement ps = c.prepareStatement(
                     "SELECT user_id, user_name, user_type, status, created_date " +
                             "FROM user_info " +
                             "ORDER BY " +
                             "  CASE user_type WHEN 'COMPANY_ADMIN' THEN 0 WHEN 'ADMIN' THEN 1 ELSE 2 END, " +
                             "  created_date DESC");
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("user_id", rs.getString("user_id"));
                row.put("user_name", rs.getString("user_name"));
                row.put("user_type", rs.getString("user_type"));
                row.put("status", rs.getString("status"));
                row.put("created_date", rs.getTimestamp("created_date"));
                out.add(row);
            }
        } catch (SQLException e) {
            log.error("[CompanyMembers] list failed db={} err={}", dbName, e.getMessage());
        }
        return out;
    }
}
