<?php

namespace Tests\Feature;

use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
use Tests\TestCase;
use App\Models\{Account,Group,Invoice,Product,Service,Site};

class InvoiceTest extends TestCase
{
	use DatabaseTransactions;

	private array $setup;

	private function account_setup(): void
	{
		$this->setup['account'] = [
			'a'=>Account::factory()->create(['site_id'=>Arr::get($this->setup,'site.a')->site_id]),
			'b'=>Account::factory()->create(['site_id'=>Arr::get($this->setup,'site.b')->site_id])
		];
	}

	private function site_setup(): void
	{
		$this->setup['site'] = [
			'a'=>Site::factory()->create(['url'=>'Test A']),
			'b'=>Site::factory()->create(['url'=>'Test B'])
		];

		Group::factory()->create(['site_id'=>Arr::get($this->setup,'site.a')->site_id]);
		Group::factory()->create(['site_id'=>Arr::get($this->setup,'site.b')->site_id]);
	}

	/**
	 * A basic feature test example.
	 *
	 * @return void
	 */
	public function testInvoiceAmount()
	{
		$this->site_setup();
		$this->account_setup();

		// @todo This test description doesnt reflect what is tested - this needs to be reworked.
		// Create two services for the same account
		// First service was billed a month ago, so this invoice will have 1 service charge
		$po = Product::factory()->notStrict()->create([
			'site_id'=>Arr::get($this->setup,'site.a')->site_id,
		]);
		$o = Service::factory()->create([
			'site_id'=>Arr::get($this->setup,'site.a')->site_id,
			'account_id'=>Arr::get($this->setup,'account.a')->id,
			'product_id'=>$po->id,
			'recur_schedule'=>Invoice::BILL_MONTHLY,
			'start_at'=>Carbon::now()->addMonth()->startofMonth(),
		]);

		$o->setRelation('product',$po);
		Config::set('site',Arr::get($this->setup,'site.a'));

		$this->assertEquals(110,$o->next_invoice_items(FALSE)->sum('total'),'Invoice Equals 110');

		/*
		// Second service wasnt billed, connected 1.5 months ago, so invoice will have 2 service charges - 1 x 0.5 month and 1 x full month. and a connection charge
		$o = factory(Service::class)->states('new-connect')->make();
		$o->setRelation('product',factory(Product::class)->states('strict')->make());
		$this->assertEqualsWithDelta(110+110+55+55,$o->next_invoice_items(FALSE)->sum('total'),2.5,'Invoice Equals 220');
		*/
	}
}