package com.cameleer.server.app.storage;

import com.cameleer.server.core.rbac.ClaimMappingRepository;
import com.cameleer.server.core.rbac.ClaimMappingRule;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

public class PostgresClaimMappingRepository implements ClaimMappingRepository {

    private final JdbcTemplate jdbc;

    public PostgresClaimMappingRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    @Override
    public List<ClaimMappingRule> findAll() {
        return jdbc.query("""
                SELECT id, claim, match_type, match_value, action, target, priority, created_at
                FROM claim_mapping_rules ORDER BY priority, created_at
                """, (rs, i) -> new ClaimMappingRule(
                rs.getObject("id", UUID.class),
                rs.getString("claim"),
                rs.getString("match_type"),
                rs.getString("match_value"),
                rs.getString("action"),
                rs.getString("target"),
                rs.getInt("priority"),
                rs.getTimestamp("created_at").toInstant()
        ));
    }

    @Override
    public Optional<ClaimMappingRule> findById(UUID id) {
        var results = jdbc.query("""
                SELECT id, claim, match_type, match_value, action, target, priority, created_at
                FROM claim_mapping_rules WHERE id = ?
                """, (rs, i) -> new ClaimMappingRule(
                rs.getObject("id", UUID.class),
                rs.getString("claim"),
                rs.getString("match_type"),
                rs.getString("match_value"),
                rs.getString("action"),
                rs.getString("target"),
                rs.getInt("priority"),
                rs.getTimestamp("created_at").toInstant()
        ), id);
        return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0));
    }

    @Override
    public UUID create(String claim, String matchType, String matchValue, String action, String target, int priority) {
        UUID id = UUID.randomUUID();
        jdbc.update("""
                INSERT INTO claim_mapping_rules (id, claim, match_type, match_value, action, target, priority)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                """, id, claim, matchType, matchValue, action, target, priority);
        return id;
    }

    @Override
    public void update(UUID id, String claim, String matchType, String matchValue, String action, String target, int priority) {
        jdbc.update("""
                UPDATE claim_mapping_rules
                SET claim = ?, match_type = ?, match_value = ?, action = ?, target = ?, priority = ?
                WHERE id = ?
                """, claim, matchType, matchValue, action, target, priority, id);
    }

    @Override
    public void delete(UUID id) {
        jdbc.update("DELETE FROM claim_mapping_rules WHERE id = ?", id);
    }
}
