<?php

declare(strict_types=1);

use App\Models\Project;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SharesSupplierPdo;

uses(DatabaseTransactions::class);
uses(SharesSupplierPdo::class);

beforeEach(function () {
    DB::statement("SELECT set_config('app.current_tenant_id', '0', true)");
});

test('resets delivered_today to 0 across all tenants', function () {
    $t1 = Tenant::factory()->create();
    $t2 = Tenant::factory()->create();

    Project::factory()->create(['tenant_id' => $t1->id, 'delivered_today' => 5]);
    Project::factory()->create(['tenant_id' => $t1->id, 'delivered_today' => 3]);
    Project::factory()->create(['tenant_id' => $t2->id, 'delivered_today' => 10]);

    $this->artisan('projects:reset-delivered-today')->assertSuccessful();

    $row = DB::selectOne('SELECT COUNT(*) FILTER (WHERE delivered_today = 0) AS c, COUNT(*) AS total FROM projects');
    expect($row->c)->toBe($row->total);
});

test('does not touch delivered_in_month', function () {
    $t = Tenant::factory()->create();
    Project::factory()->create([
        'tenant_id' => $t->id,
        'delivered_today' => 5,
        'delivered_in_month' => 50,
    ]);

    $this->artisan('projects:reset-delivered-today')->assertSuccessful();

    $row = DB::selectOne('SELECT delivered_today, delivered_in_month FROM projects ORDER BY id DESC LIMIT 1');
    expect((int) $row->delivered_today)->toBe(0);
    expect((int) $row->delivered_in_month)->toBe(50);
});
