<?php

namespace Tests\Feature;

use App\Models\Employee;
use App\Models\OfficeLocation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class WhatsAppWebhookTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_webhook_can_automatically_process_checkin_from_location(): void
    {
        $employee = Employee::where('email', 'joko.widodo@absensi.test')->first();
        $office = OfficeLocation::first();

        // Simulate employee sending WhatsApp location attachment
        $response = $this->postJson('/api/whatsapp/webhook', [
            'sender' => $employee->phone,
            'location' => "{$office->latitude},{$office->longitude}",
            'message' => '',
        ]);

        $response->assertStatus(200);
        $response->assertJson([
            'status' => true,
            'action' => 'check_in',
            'employee' => $employee->name,
        ]);

        $this->assertDatabaseHas('attendances', [
            'employee_id' => $employee->id,
            'office_location_id' => $office->id,
        ]);
    }

    public function test_webhook_can_automatically_process_checkout_on_second_location(): void
    {
        $employee = Employee::where('email', 'joko.widodo@absensi.test')->first();
        $office = OfficeLocation::first();

        // 1st time: Check-In
        $this->postJson('/api/whatsapp/webhook', [
            'sender' => $employee->phone,
            'location' => "{$office->latitude},{$office->longitude}",
        ]);

        // 2nd time: Check-Out
        $response = $this->postJson('/api/whatsapp/webhook', [
            'sender' => $employee->phone,
            'location' => "{$office->latitude},{$office->longitude}",
        ]);

        $response->assertStatus(200);
        $response->assertJson([
            'status' => true,
            'action' => 'check_out',
            'employee' => $employee->name,
        ]);
    }

    public function test_webhook_handles_unregistered_phone(): void
    {
        $response = $this->postJson('/api/whatsapp/webhook', [
            'sender' => '089999999999',
            'location' => '-6.2088,106.8456',
        ]);

        $response->assertStatus(200);
        $response->assertJson([
            'status' => false,
        ]);
    }
}
