package com.writeoff.security;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Component
public class PasswordStorageMigrationRunner implements ApplicationRunner {
    private final JdbcTemplate jdbcTemplate;
    private final PasswordCodecService passwordCodecService;

    public PasswordStorageMigrationRunner(JdbcTemplate jdbcTemplate, PasswordCodecService passwordCodecService) {
        this.jdbcTemplate = jdbcTemplate;
        this.passwordCodecService = passwordCodecService;
    }

    @Override
    public void run(ApplicationArguments args) {
        migrateTenantUsers();
        migratePlatformUsers();
    }

    private void migrateTenantUsers() {
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(
                "SELECT id, phone, password_hash, tenant_switch_account_key FROM sys_user WHERE is_deleted=0"
        );
        Map<String, String> sharedKeys = new LinkedHashMap<String, String>();
        for (Map<String, Object> row : rows) {
            String currentPassword = row.get("password_hash") == null ? "" : String.valueOf(row.get("password_hash"));
            if (passwordCodecService.isEncoded(currentPassword)) {
                continue;
            }
            String phone = row.get("phone") == null ? "" : String.valueOf(row.get("phone")).trim();
            String legacyKey = phone + "|" + currentPassword;
            String existingSwitchKey = row.get("tenant_switch_account_key") == null ? "" : String.valueOf(row.get("tenant_switch_account_key")).trim();
            String sharedKey = sharedKeys.get(legacyKey);
            if (sharedKey == null || sharedKey.isEmpty()) {
                sharedKey = existingSwitchKey.isEmpty()
                        ? "acct_" + UUID.randomUUID().toString().replace("-", "").toUpperCase()
                        : existingSwitchKey;
                sharedKeys.put(legacyKey, sharedKey);
            }
            jdbcTemplate.update(
                    "UPDATE sys_user SET password_hash=?, tenant_switch_account_key=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
                    passwordCodecService.encode(currentPassword),
                    sharedKey,
                    ((Number) row.get("id")).longValue()
            );
        }
    }

    private void migratePlatformUsers() {
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(
                "SELECT id, password_hash FROM platform_user WHERE is_deleted=0"
        );
        for (Map<String, Object> row : rows) {
            String currentPassword = row.get("password_hash") == null ? "" : String.valueOf(row.get("password_hash"));
            if (passwordCodecService.isEncoded(currentPassword)) {
                continue;
            }
            jdbcTemplate.update(
                    "UPDATE platform_user SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
                    passwordCodecService.encode(currentPassword),
                    ((Number) row.get("id")).longValue()
            );
        }
    }
}
