package Bif::Sync::Plugin::Repo;
use strict;
use warnings;
use DBIx::ThinSQL qw/qv sq/;
use Log::Any '$log';

our $VERSION = '0.1.5_5';

sub Bif::Sync::real_import_hub {
    my $self   = shift;
    my $uuid   = shift;
    my $result = $self->recv_changesets;

    if ( $result eq 'RecvChangesets' ) {
        my ($ref) = $self->db->uuid2id($uuid);
        return 'IDNotFound' unless $ref;

        # Set projects.default_hub_id to this hub for the projects that
        # came along for the ride
        $self->db->xdo(
            with => 'x',
            as   => sq(
                select     => 'p.id',
                from       => 'project_hubs ph',
                inner_join => 'projects p',
                on    => 'p.id = ph.project_id AND p.default_hub_id IS NULL',
                where => { 'ph.hub_id' => $ref->[0] },
            ),
            update => 'projects',
            set    => { default_hub_id => $ref->[0] },
            where  => 'id IN (SELECT id FROM x)',
        );
        return ( 'RepoImported', $ref );
    }
    return $result;
}

sub Bif::Sync::real_transfer_hub_changes {
    my $self = shift;

    my $tmp   = $self->temp_table;
    my $total = $self->db->xval(
        select => 'COUNT(t.id)',
        from   => "$tmp t",
    );

    my $r = $self->exchange_changesets(
        $total,
        [
            select   => 't.id AS id',
            from     => "$tmp t",
            order_by => 't.id ASC',
        ],
    );

    $self->db->xdo( delete_from => $tmp );

    # Set projects.default_hub_id to this hub for the projects that
    # came along for the ride
    $self->db->xdo(
        with => 'x',
        as   => sq(
            select     => 'p.id',
            from       => 'project_hubs ph',
            inner_join => 'projects p',
            on         => 'p.id = ph.project_id AND p.default_hub_id IS NULL',
            where      => { 'ph.hub_id' => $self->hub_id },
        ),
        update => 'projects',
        set    => { default_hub_id => $self->hub_id },
        where  => 'id IN (SELECT id FROM x)',
    );

    return $r unless $r eq 'ExchangeChangesets';
    return 'TransferHubChanges';
}

sub Bif::Sync::real_export_hub {
    my $self = shift;
    my $id   = shift;

    my $total = $self->db->xval(
        select => 'h.num_changes',
        from   => 'hubs h',
        where  => { 'h.id' => $id },
    );

    my $recv = $self->send_changesets(
        $total,
        [
            select => 'hc.change_id AS id',
            from   => 'hub_related_changes hc',
            where  => {
                'hc.hub_id'      => $id,
                'hc.change_id !' => undef,
            },
            order_by => 'hc.change_id ASC',
        ]
    );

    return 'RepoExported' if $recv eq 'ChangesetsSent';
    return $recv;
}

1;

=head1 NAME

=for bif-doc #perl

Bif::Sync::Plugin::Repo - synchronisation plugin for hubs

