package com.cloudhandson.vpdbackoffice.service;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/** Resolves active HMM employee tokens using only their SHA-256 hashes in ADB. */
@Service
public class JdbcHmmMcpBearerAuthenticator implements HmmMcpBearerAuthenticator {

  private static final int MAX_TOKEN_LENGTH = 4096;

  private final JdbcTemplate jdbcTemplate;

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

  @Override
  public HmmMcpPrincipal authenticate(String bearerToken) {
    if (bearerToken == null || bearerToken.isBlank() || bearerToken.length() > MAX_TOKEN_LENGTH) {
      throw new McpUnauthorizedException();
    }
    try {
      return jdbcTemplate.queryForObject("""
          SELECT employee.employee_id,
                 employee.employee_code,
                 employee.team_id
          FROM hmm_access_bearer_tokens token
          JOIN hmm_hr_employees employee
            ON employee.employee_id = token.employee_id
          WHERE token.key_hash = STANDARD_HASH(?, 'SHA256')
            AND token.revoked_at IS NULL
            AND token.expires_at > CAST(SYSTIMESTAMP AS TIMESTAMP)
            AND employee.employment_status = 'ACTIVE'
          """, (resultSet, rowNum) -> new HmmMcpPrincipal(
          resultSet.getLong("employee_id"),
          resultSet.getString("employee_code"),
          resultSet.getObject("team_id", Long.class)
      ), bearerToken);
    } catch (EmptyResultDataAccessException exception) {
      throw new McpUnauthorizedException();
    }
  }
}
