package LasTres::Schema;

use v5.36.0;

use strict;
use warnings;

our $VERSION = 12;

use feature 'signatures';

use LasTres;

use parent 'DBIx::Class::Schema';

__PACKAGE__->load_namespaces();

my $schema;

sub Schema ($class) {
    if ( !defined $schema ) {
        my $app             = LasTres->new;
        my $config          = $app->{config};
        my $database_config = $config->{database};
        my $dbname          = $database_config->{dbname};
        my $host            = $database_config->{host};
        my $port            = $database_config->{port};
        my $user            = $database_config->{user};
        my $password        = $database_config->{password};
        my $dsn             = 'dbi:Pg:';

        if ( !defined $dbname ) {
            die "The key database/dbname must be configured.";
        }
        $dsn .= "dbname=$dbname";
        if ( defined $host ) {
            $dsn .= ";host=$host";
        }
        if ( defined $port ) {
            $dsn .= ";port=$port";
        }

        # Undef is perfectly fine for username and password.
        $schema = $class->connect(
            $dsn, $user,
            $password,
            {
                auto_savepoint => 1,
                Callbacks      => {
                    connected => sub {
                        shift->do('set timezone = UTC');
                        return;
                    }
                }
            }
        );
    }
    return $schema;
}
1;
