#!/usr/bin/perl

use strict;
use warnings;
use DBI;

print "=== autoSMART Database Test ===\n\n";

my $dsn = "DBI:Pg:dbname=autosmart;host=192.168.2.102;port=5432";
my $dbh = DBI->connect($dsn, "autosmart", "autoSMART2025!", {
    RaiseError => 1,
    AutoCommit => 1,
    PrintError => 0
}) or die "Failed to connect to database: $DBI::errstr\n";

print "✓ Database connection successful\n";

# Test tables exist
my @tables = qw(hdd_inventory hdd_migrations smart_readings predictions smart_thresholds alert_history system_config);

for my $table (@tables) {
    my $sth = $dbh->prepare("SELECT COUNT(*) FROM $table");
    $sth->execute();
    my ($count) = $sth->fetchrow_array();
    print "✓ Table $table: $count rows\n";
}

# Test views
my @views = qw(smart_readings_reconstructed latest_smart_readings drive_health_summary);

for my $view (@views) {
    eval {
        my $sth = $dbh->prepare("SELECT COUNT(*) FROM $view");
        $sth->execute();
        my ($count) = $sth->fetchrow_array();
        print "✓ View $view: $count rows\n";
    };
    if ($@) {
        print "✗ View $view: ERROR - $@\n";
    }
}

# Test function
eval {
    my $sth = $dbh->prepare("SELECT should_store_smart_reading(1, '{}', 'test', NOW())");
    $sth->execute();
    print "✓ Function should_store_smart_reading: Available\n";
};
if ($@) {
    print "✗ Function should_store_smart_reading: ERROR - $@\n";
}

$dbh->disconnect();

print "\n=== Test Complete ===\n";
