<?php

namespace Tests\Feature\Location;

use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\CIUnitTestCase;
use Firebase\JWT\JWT;

class LocationPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected string $token;
    protected string $endpoint = 'api/location';

    protected function setUp(): void
    {
        parent::setUp();
        $key = getenv('JWT_SECRET') ?: 'my-secret-key';
        $payload = [
            'iss' => 'localhost',
            'aud' => 'localhost',
            'iat' => time(),
            'nbf' => time(),
            'exp' => time() + 3600,
            'uid' => 1,
            'email' => 'admin@admin.com',
        ];
        $this->token = JWT::encode($payload, $key, 'HS256');
    }

    private function authHeaders(): array
    {
        return ['Cookie' => 'token=' . $this->token];
    }

    private function createLocation(array $data = []): array
    {
        $payload = array_merge([
            'LocCode' => 'LC' . substr(uniqid(), -4),
            'LocFull' => 'Test Location ' . uniqid(),
        ], $data);

        $response = $this->withHeaders($this->authHeaders())
                         ->withBodyFormat('json')
                         ->call('post', $this->endpoint, $payload);

        $response->assertStatus(201);
        $decoded = json_decode($response->getJSON(), true);
        $locationId = $decoded['data']['LocationID'];
        $show = $this->withHeaders($this->authHeaders())
                     ->call('get', "{$this->endpoint}/{$locationId}");
        $show->assertStatus(200);
        $showData = json_decode($show->getJSON(), true)['data'];
        return $showData;
    }

    public function testPartialUpdateLocationSuccess()
    {
        $location = $this->createLocation();
        $id = $location['LocationID'];

        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/{$id}", ['LocFull' => 'Updated Location']);

        $patch->assertStatus(200);
        $patchData = json_decode($patch->getJSON(), true);
        $this->assertEquals('success', $patchData['status']);

        $show = $this->withHeaders($this->authHeaders())->call('get', "{$this->endpoint}/{$id}");
        $show->assertStatus(200);
        $showData = json_decode($show->getJSON(), true)['data'];

        $this->assertEquals('Updated Location', $showData['LocFull']);
        $this->assertEquals($location['LocCode'], $showData['LocCode']);
    }

    public function testPartialUpdateLocationNotFound()
    {
        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/999999", ['LocFull' => 'Updated']);

        $patch->assertStatus(404);
    }

    public function testPartialUpdateLocationInvalidId()
    {
        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/invalid", ['LocFull' => 'Updated']);

        $patch->assertStatus(400);
    }

    public function testPartialUpdateLocationEmptyPayload()
    {
        $location = $this->createLocation();
        $id = $location['LocationID'];

        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/{$id}", []);

        $patch->assertStatus(400);
    }

    public function testPartialUpdateLocationSingleField()
    {
        $location = $this->createLocation();
        $id = $location['LocationID'];

        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/{$id}", ['LocCode' => 'LC' . substr(uniqid(), -4)]);

        $patch->assertStatus(200);
        $showData = json_decode($this->withHeaders($this->authHeaders())
                                     ->call('get', "{$this->endpoint}/{$id}")
                                     ->getJSON(), true)['data'];

        $this->assertNotEquals($location['LocCode'], $showData['LocCode']);
        $this->assertEquals($location['LocFull'], $showData['LocFull']);

    }

    public function testPartialUpdateLocationAddressField()
    {
        $location = $this->createLocation();
        $id = $location['LocationID'];

        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/{$id}", ['Street1' => '123 Market St']);

        $patch->assertStatus(200);
        $showData = json_decode($this->withHeaders($this->authHeaders())
                                      ->call('get', "{$this->endpoint}/{$id}")
                                      ->getJSON(), true)['data'];

        $this->assertEquals('123 Market St', $showData['Street1']);
    }
}
