package com.writeoff.module.audit.service;

import com.writeoff.module.audit.model.AuditNode;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class AuditFlowConfigService {
    private final JdbcTemplate jdbcTemplate;

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

    public List<AuditNode> getEnabledNodes(Long tenantId) {
        List<String> codes = jdbcTemplate.queryForList(
                "SELECT n.node_code FROM audit_flow f " +
                        "JOIN audit_flow_node n ON f.id=n.flow_id " +
                        "WHERE f.tenant_id=? AND f.is_default=1 AND f.status='ENABLED' AND n.status='ENABLED' " +
                        "ORDER BY n.sort_no ASC",
                String.class,
                tenantId
        );
        List<AuditNode> result = new ArrayList<>();
        for (String code : codes) {
            result.add(AuditNode.valueOf(code));
        }
        if (result.isEmpty()) {
            result.add(AuditNode.INIT_REVIEW);
            result.add(AuditNode.RE_REVIEW);
            result.add(AuditNode.FINAL_REVIEW);
        }
        return result;
    }

    public AuditNode firstNode(Long tenantId) {
        return getEnabledNodes(tenantId).get(0);
    }

    public AuditNode nextNode(Long tenantId, AuditNode current) {
        List<AuditNode> nodes = getEnabledNodes(tenantId);
        for (int i = 0; i < nodes.size(); i++) {
            if (nodes.get(i) == current) {
                if (i + 1 < nodes.size()) {
                    return nodes.get(i + 1);
                }
                return null;
            }
        }
        return null;
    }

    public Long resolveAssigneeUserId(Long tenantId, AuditNode node) {
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(
                "SELECT a.assignee_type, a.assignee_ref_id FROM audit_flow f " +
                        "JOIN audit_flow_node n ON f.id=n.flow_id " +
                        "LEFT JOIN audit_flow_node_assignee a ON n.id=a.flow_node_id " +
                        "WHERE f.tenant_id=? AND f.is_default=1 AND f.status='ENABLED' AND n.status='ENABLED' AND n.node_code=? " +
                        "ORDER BY a.id ASC LIMIT 1",
                tenantId,
                node.name()
        );
        if (rows.isEmpty()) {
            return null;
        }
        String assigneeType = rows.get(0).get("assignee_type") == null ? null : String.valueOf(rows.get(0).get("assignee_type"));
        Object ref = rows.get(0).get("assignee_ref_id");
        if ("USER".equals(assigneeType) && ref != null) {
            return ((Number) ref).longValue();
        }
        if ("ROLE".equals(assigneeType) && ref != null) {
            List<Long> userIds = jdbcTemplate.queryForList(
                    "SELECT ur.user_id FROM user_role ur " +
                            "JOIN sys_user u ON ur.user_id=u.id " +
                            "WHERE ur.tenant_id=? AND ur.role_id=? AND u.status='ENABLED' AND u.is_deleted=0 " +
                            "ORDER BY ur.user_id ASC LIMIT 1",
                    Long.class,
                    tenantId,
                    ((Number) ref).longValue()
            );
            return userIds.isEmpty() ? null : userIds.get(0);
        }
        return null;
    }
}
