package com.cloudhandson.ddsbackoffice.service;

import com.cloudhandson.ddsbackoffice.domain.DdsGrantInventoryEntry;
import com.cloudhandson.ddsbackoffice.domain.DdsGrantInventorySnapshot;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * Uses the same DDS inventory source already used by the setup SQL. The catalog does not expose
 * every predicate detail here, so a successful read is deliberately reported as partial evidence.
 */
@Service
public class JdbcDdsGrantInventory implements DdsGrantInventory {

  private final JdbcTemplate jdbcTemplate;

  public JdbcDdsGrantInventory(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public DdsGrantInventorySnapshot observe(String protectedObject) {
    String objectName = protectedObject.substring(protectedObject.lastIndexOf('.') + 1)
        .toUpperCase(Locale.ROOT);
    try {
      List<DdsGrantInventoryEntry> grants = jdbcTemplate.query("""
          SELECT grant_name, object_name, grantee
          FROM dba_data_grants
          WHERE object_name = ?
          ORDER BY grant_name
          """, (row, ignored) -> new DdsGrantInventoryEntry(
          row.getString("grant_name"), row.getString("object_name"), row.getString("grantee")
      ), objectName);
      return new DdsGrantInventorySnapshot(true, grants, Instant.now(), "");
    } catch (DataAccessException exception) {
      return new DdsGrantInventorySnapshot(false, List.of(), Instant.now(),
          "DDS Grant 목록을 읽을 수 없습니다. DB 연결 또는 catalog 조회 권한을 확인하세요.");
    }
  }
}
