<?php

namespace Tests\Feature;

use App\Models\Branch;
use App\Models\Business;
use App\Models\DailyBranchReport;
use App\Models\DailyClosing;
use App\Models\Role;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

class DailyBranchReportObserverTest extends TestCase
{
    use DatabaseMigrations;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(DatabaseSeeder::class);
    }

    public function test_manager_confirmation_automatically_archives_the_daily_branch_report(): void
    {
        Queue::fake();
        $business = Business::firstOrFail();
        $branch = Branch::create([
            'business_id' => $business->id,
            'name' => 'Observer Report Branch',
            'status' => 'active',
        ]);
        $manager = User::factory()->create([
            'name' => 'Observer Manager',
            'username' => 'observer_report_manager',
            'status' => 'active',
            'primary_branch_id' => $branch->id,
        ]);
        $manager->roles()->attach(Role::where('name', 'branch-manager')->firstOrFail());
        $manager->branches()->attach($branch->id, ['is_primary' => true]);

        $closing = DailyClosing::withoutGlobalScopes()->create([
            'closing_number' => 'CLS-OBSERVER-001',
            'business_id' => $business->id,
            'branch_id' => $branch->id,
            'closing_date' => '2026-08-17',
            'status' => 'prepared',
            'opening_funds' => '1000.00',
            'collections' => '200.00',
            'closing_funds' => '1200.00',
            'expected_cash' => '1200.00',
            'actual_cash' => '1200.00',
            'variance' => '0.00',
            'snapshot_fingerprint' => hash('sha256', 'observer-closing'),
            'snapshot' => ['transaction_count' => 2],
            'prepared_by' => $manager->id,
            'prepared_at' => now()->subMinute(),
        ]);

        $closing->update([
            'status' => 'confirmed',
            'manager_confirmed_by' => $manager->id,
            'manager_confirmed_at' => now(),
        ]);

        $report = DailyBranchReport::firstOrFail();
        $this->assertSame($closing->id, $report->daily_closing_id);
        $this->assertSame($branch->id, $report->branch_id);
        $this->assertSame('confirmed', $report->snapshot['status']);
        $this->assertSame('Observer Manager', $report->snapshot['confirmed_by']);
        $this->assertNotEmpty($report->body_html);
        $this->assertNotEmpty($report->body_text);
        $this->assertNotEmpty($report->checksum);
    }
}
