<?php

namespace Tests\Feature;

use App\Models\Member;
use App\Models\Organization;
use App\Models\User;
use App\Services\Events\ServiceEventSignature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareServiceEventTest extends TestCase
{
    use RefreshDatabase;

    protected string $secret = 'test-service-events-secret';

    protected function setUp(): void
    {
        parent::setUp();
        config(['service_events.inbound_secret' => $this->secret]);
    }

    public function test_rejects_invalid_signature(): void
    {
        $this->postJson('/api/service-events', [
            'event' => 'user.deleted',
            'data' => ['user' => 'user-001'],
        ], ['X-Ladill-Signature' => 'sha256=bad'])
            ->assertUnauthorized();
    }

    public function test_user_deleted_event_removes_local_mirror(): void
    {
        $user = User::create([
            'public_id' => 'user-001',
            'name' => 'Deleted User',
            'email' => 'deleted@example.com',
        ]);

        $organization = Organization::create([
            'owner_ref' => 'owner-001',
            'name' => 'Test Clinic',
            'slug' => 'test-clinic',
            'timezone' => 'UTC',
            'settings' => ['onboarded' => true],
        ]);

        Member::create([
            'owner_ref' => 'owner-001',
            'organization_id' => $organization->id,
            'user_ref' => 'user-001',
            'role' => 'doctor',
        ]);

        $payload = json_encode([
            'event' => 'user.deleted',
            'data' => ['user' => 'user-001'],
        ], JSON_THROW_ON_ERROR);

        $this->postJson('/api/service-events', json_decode($payload, true), [
            'X-Ladill-Signature' => ServiceEventSignature::sign($payload, $this->secret),
            'X-Ladill-Event-Id' => 'evt-delete-001',
        ])->assertOk()->assertJson(['status' => 'accepted']);

        $this->assertDatabaseMissing('users', ['public_id' => 'user-001']);
        $this->assertDatabaseMissing('care_members', ['user_ref' => 'user-001']);
    }

    public function test_organization_updated_event_syncs_name(): void
    {
        Organization::create([
            'owner_ref' => 'owner-001',
            'name' => 'Old Name',
            'slug' => 'old-name',
            'timezone' => 'UTC',
            'settings' => ['onboarded' => true],
        ]);

        $payload = json_encode([
            'event' => 'organization.updated',
            'data' => ['owner' => 'owner-001', 'name' => 'New Clinic Name'],
        ], JSON_THROW_ON_ERROR);

        $this->postJson('/api/service-events', json_decode($payload, true), [
            'X-Ladill-Signature' => ServiceEventSignature::sign($payload, $this->secret),
        ])->assertOk();

        $this->assertDatabaseHas('care_organizations', [
            'owner_ref' => 'owner-001',
            'name' => 'New Clinic Name',
        ]);
    }
}
