use strict;
use warnings;

our @Initial = (
    sub {
        my $users = RT::Users->new( RT->SystemUser );
        $users->FindAllRows;

        my $attributes = $users->Join(
            ALIAS1 => "main",
            FIELD1 => "id",
            TABLE2 => RT::Attributes->Table,
            FIELD2 => "ObjectId",
        );
        $users->Limit(
            ALIAS => $attributes,
            FIELD => "ObjectType",
            VALUE => "RT::User",
        );
        $users->Limit(
            ALIAS => $attributes,
            FIELD => "Name",
            VALUE => RT::User::_PrefName( RT->System ),
        );

        # Iterate all users (including disabled), with config preferences set.
        # Avoids running a query for every user in the system by only selecting
        # those known to have preferences.
        while ( my $user = $users->Next ) {
            RT->Logger->debug( sprintf "User #%d has config preferences", $user->id );

            my $config = $user->Preferences( RT->System ) or next;
            my $style  = $config->{WebDefaultStylesheet}  or next;

            if ( $style =~ /^elevator-(light|dark)$/ ) {
                $config->{WebDefaultStylesheet} = 'elevator';
                $config->{WebDefaultThemeMode}  = $1;
                my ( $ret, $msg ) = $user->SetPreferences( RT->System, $config );
                if ($ret) {
                    RT->Logger->debug( sprintf "Updated config Preferences for user %s (#%d)",
                        $user->Name, $user->id );
                }
                else {
                    RT->Logger->error( sprintf "Could not update config Preferences for user %s (#%d)",
                        $user->Name, $user->id );
                }
            }

        }
    },
    sub {
        # Update theme and mode settings if needed
        my $config = RT::Configuration->new( RT->SystemUser );
        my ( $ok, $msg ) = $config->LoadByCols( Name => 'WebDefaultStylesheet', Disabled => '0' );

        if ( $ok && $config->Id ) {

            # The system has a custom stylesheet setting in the DB. Update for new naming and set
            # the mode appropriately.

            if ( $config->_Value('Content') =~ /^elevator-(light|dark)$/ ) {
                ( $ok, $msg ) = $config->SetContent('elevator');
                RT->Logger->error("Unable to reset WebDefaultStylesheet: $msg") unless $ok;

                # ThemeMode is new, so set it based on the previous value.
                my $mode = RT::Configuration->new( RT->SystemUser );
                ( $ok, $msg ) = $mode->Create( Name => 'WebDefaultThemeMode', Content => $1 );
                RT->Logger->error("Unable to set WebDefaultThemeMode: $msg") unless $ok;
            }
        }
    },
);

1;
