<?php

namespace Tests\Feature;

use App\Models\Product;
use App\Models\StockLevel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ReportsApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_daily_sales_report_can_be_refreshed_from_orders(): void
    {
        ['company' => $company, 'user' => $user, 'branch' => $branch] = $this->createUserWithPermissions([
            'shifts.manage',
            'orders.manage',
            'payments.manage',
            'reports.view',
        ]);

        $paymentMethod = $this->createPaymentMethod($company);
        $product = Product::factory()->create([
            'company_id' => $company->id,
            'name' => 'Milk',
            'selling_price' => 120,
            'cost_price' => 80,
        ]);

        StockLevel::create([
            'branch_id' => $branch->id,
            'product_id' => $product->id,
            'quantity' => 20,
            'reserved_quantity' => 0,
        ]);

        $this->actingAsApi($user, $branch->id)
            ->postJson('/api/v1/shifts/open', [])
            ->assertCreated();

        $this->actingAsApi($user, $branch->id)
            ->postJson('/api/v1/orders', [
                'items' => [
                    [
                        'product_id' => $product->id,
                        'quantity' => 2,
                    ],
                ],
                'payments' => [
                    [
                        'payment_method_id' => $paymentMethod->id,
                        'amount' => 240,
                    ],
                ],
            ])
            ->assertCreated();

        $report = $this->actingAsApi($user, $branch->id)
            ->getJson('/api/v1/reports/daily-sales?refresh=1&date_from='.now()->toDateString().'&date_to='.now()->toDateString());

        $report->assertOk()
            ->assertJsonPath('data.0.total_orders', 1)
            ->assertJsonPath('data.0.net_sales', '240.0000');
    }
}
