#!/usr/bin/env perl

use strict;
use warnings;

use Mojo::File qw(curfile);
use lib curfile->dirname->sibling('lib')->to_string;

use Mojo::Pg;
use SeMeet::Schema;
use SeMeet::Model::IAPI;

my $iapi = SeMeet::Model::IAPI->new( $ENV{CFG_IAPI} );
my $schema = SeMeet::Schema->connect({
    dsn            => $ENV{CFG_DB_DSN},
    user           => $ENV{CFG_DB_USERNAME},
    password       => $ENV{CFG_DB_PASSWORD},
    AutoCommit     => 1,
    quote_char     => '"',
    name_sep       => '.',
    pg_enable_utf8 => 1,
    on_connect_do  => [
        "set timezone to 'Europe/Prague'",
    ],
  }
);

my $octopus_groups = $iapi->get('octopus/groups/');

my @exists = ();

my $guard  = $schema->txn_scope_guard;

# Insert/Update
GROUP:
foreach my $group ( @{ $octopus_groups } ) {

    push @exists, $group->{id};

    $schema->resultset('Group')->update_or_create(
        {
            octid => $group->{id},
            name  => $group->{name},
        },
        { key => 'octid'}
    );
}

# Cleanup
$schema->resultset('Group')->search({octid => {-not_in => \@exists}})->delete;

# Update cache
my $meets = $schema->resultset('Meet')->search({deleted => undef});

MEET:
while ( my $meet = $meets->next ) {
    $meet->update_groups_cache();
}

$guard->commit;