<?php

namespace Tests;

use App\Models\Branch;
use App\Models\Company;
use App\Models\PaymentMethod;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Database\Seeders\ReferenceDataSeeder;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    protected function seedReferenceData(): void
    {
        $this->seed(ReferenceDataSeeder::class);
    }

    protected function createUserWithPermissions(array $permissionSlugs): array
    {
        $this->seedReferenceData();

        $company = Company::factory()->create();
        $branch = Branch::factory()->create([
            'company_id' => $company->id,
        ]);
        $role = Role::factory()->create([
            'company_id' => $company->id,
            'name' => 'Administrator',
            'slug' => 'administrator',
        ]);

        $permissions = Permission::query()
            ->whereIn('slug', $permissionSlugs)
            ->pluck('id');

        $role->permissions()->sync($permissions);

        $user = User::factory()->create([
            'company_id' => $company->id,
            'branch_id' => $branch->id,
            'role_id' => $role->id,
            'email' => 'admin@example.com',
            'password' => 'password',
            'pin' => '1234',
        ]);

        return compact('company', 'branch', 'role', 'user');
    }

    protected function createPaymentMethod(Company $company, string $type = 'cash', string $name = 'Cash'): PaymentMethod
    {
        return PaymentMethod::factory()->create([
            'company_id' => $company->id,
            'type' => $type,
            'name' => $name,
        ]);
    }

    protected function actingAsApi(User $user, ?int $branchId = null): static
    {
        $token = $user->createToken('test-suite')->plainTextToken;

        return $this
            ->withHeader('Authorization', 'Bearer '.$token)
            ->withHeader('X-Branch-Id', (string) ($branchId ?? $user->branch_id));
    }
}
