<?php

namespace PortalPeople\AuthRedirect\Test;

use Magento\Framework\App\ObjectManager;
use PortalPeople\AuthRedirect\Helper\SimpleLoginAttemptHelper;

class TestDatabaseLoggingDdl
{
    public static function run()
    {
        echo "=== Testing Database Logging ===\n\n";

        $objectManager = ObjectManager::getInstance();

        // Test database connection
        $resource = $objectManager->get(\Magento\Framework\App\ResourceConnection::class);
        $connection = $resource->getConnection();

        // Check if table exists
        $tableName = $resource->getTableName('portalpeople_login_attempt_logger');
        $tableExists = $connection->isTableExists($tableName);

        echo "Table name: " . $tableName . "\n";
        echo "Table exists: " . ($tableExists ? "YES" : "NO") . "\n\n";

        if (!$tableExists) {
            echo "ERROR: Table does not exist. Run setup:upgrade first.\n";
            return;
        }

        // Show table structure
        $describe = $connection->describeTable($tableName);
        echo "Table structure:\n";
        foreach ($describe as $column => $info) {
            echo "- " . $column . " (" . $info['DATA_TYPE'] . ")\n";
        }
        echo "\n";

        // Test direct database insert
        try {
            $connection->insert($tableName, [
                'email' => 'direct-test@example.com',
                'ip_address' => '127.0.0.1',
                'was_successful' => 0,
                'attempted_at' => date('Y-m-d H:i:s')
            ]);
            echo "Direct database insert: SUCCESS\n";
        } catch (\Exception $e) {
            echo "Direct database insert: FAILED - " . $e->getMessage() . "\n";
        }

        // Test helper logging
        try {
            $helper = $objectManager->get(SimpleLoginAttemptHelper::class);
            $helper->logAttempt('helper-test@example.com', false);
            echo "Helper logging: SUCCESS\n";
        } catch (\Exception $e) {
            echo "Helper logging: FAILED - " . $e->getMessage() . "\n";
        }

        // Check records
        $select = $connection->select()->from($tableName)->order('attempted_at DESC')->limit(5);
        $records = $connection->fetchAll($select);

        echo "\nRecent records (" . count($records) . " found):\n";
        foreach ($records as $record) {
            echo sprintf(
                "Email: %s, IP: %s, Success: %s, Time: %s\n",
                $record['email'],
                $record['ip_address'],
                $record['was_successful'] ? 'Yes' : 'No',
                $record['attempted_at']
            );
        }
    }
}