#!/usr/bin/perl

use strict;
use warnings;

use Test::More;
use Test::Async::HTTP 0.02; # ->GET
use t::Util;

use IO::Async::Loop;
use Net::Async::Matrix;
use Future;

my $matrix = Net::Async::Matrix->new(
   ua => my $ua = Test::Async::HTTP->new,
   server => "localserver.test",

   make_delay => sub { Future->new },
);

IO::Async::Loop->new->add( $matrix ); # for ->loop->new_future
matrix_login( $matrix, $ua );

# join by direct ID
{
   my $f = $matrix->join_room( "!abcdef12345:localserver.test" );
   ok( defined $f, '$f from ->join_room' );

   ok( my $p = next_pending_not_events( $ua ), '->join_room ID sends an HTTP request' );

   is( $p->request->method, "POST", '$req->method' );
   my $uri = $p->request->uri;
   is( $uri->authority, "localserver.test", '$req->uri->authority' );
   is( $uri->path,      "/_matrix/client/api/v1/join/!abcdef12345:localserver.test",
      '$req->uri->path' );

   respond_json( $p, { room_id => "!abcdef12345:localserver.test" } );

   ok( $p = next_pending_not_events( $ua ), '->join_room ID sends a second HTTP request' );
   is( $p->request->method, "GET", '$req->method' );
   $uri = $p->request->uri;
   is( $uri->path, "/_matrix/client/api/v1/rooms/!abcdef12345:localserver.test/state", '$req->uri->path' );

   respond_json( $p, [] );

   ok( $f->is_ready, '$f now ready after /state response' );
   isa_ok( my $room =  $f->get, "Net::Async::Matrix::Room", '$f->get returns a room' );

   ok( $room->await_synced->is_ready, '$room->await_synced is already ready' );
}

# don't try to start two initialSyncs that will race if the event stream echoes us back first
{
   my $f = $matrix->join_room( "!abcdef67890:localserver.test" );

   my $p = next_pending_not_events( $ua );
   is( $p->request->uri->path, "/_matrix/client/api/v1/join/!abcdef67890:localserver.test" );
   respond_json( $p, { room_id => "!abcdef67890:localserver.test" } );

   $p = next_pending_not_events( $ua );
   is( $p->request->uri->path, "/_matrix/client/api/v1/rooms/!abcdef67890:localserver.test/state" );

   my $join_ev = {
      type       => "m.room.member",
      room_id    => "!abcdef67890:localserver.test",
      state_key  => '@my-test-user:localserver.test',
      user_id    => '@my-test-user:localserver.test',
      membership => "join",
      content    => { membership => "join" },
   };

   send_events( $ua, $join_ev );

   # Now respond
   respond_json( $p, [ $join_ev ] );

   ok( $f->is_ready, '$f now ready after /state response after join event' );

   ok( $f->get->await_synced->is_ready, '$room->await_synced is already ready' );
}

done_testing;
