<?php

namespace Tests\Feature\Company;

use App\Models\CompanyRequest;
use App\Models\Members\User;
use App\Models\Members\UserTenant;
use App\Models\Tenants\Tenant;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;

class CompanyApiTest extends TestCase
{
    use DatabaseTransactions;

    private Tenant $tenant;

    private User $user;

    private string $apiKey;

    private string $token;

    protected function setUp(): void
    {
        parent::setUp();

        // 테스트용 API Key 생성
        $this->apiKey = 'test-api-key-'.uniqid();
        \DB::table('api_keys')->insert([
            'key' => $this->apiKey,
            'description' => 'Test API Key',
            'is_active' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Tenant 생성 또는 기존 사용
        $this->tenant = Tenant::first() ?? Tenant::withoutEvents(function () {
            return Tenant::create([
                'company_name' => 'Test Company',
                'code' => 'TEST'.uniqid(),
                'email' => 'test@example.com',
                'phone' => '010-1234-5678',
            ]);
        });

        // User 생성
        $testUserId = 'testuser'.uniqid();
        $this->user = User::create([
            'user_id' => $testUserId,
            'name' => 'Test User',
            'email' => $testUserId.'@example.com',
            'password' => bcrypt('password123'),
        ]);

        // UserTenant 관계 생성
        UserTenant::create([
            'user_id' => $this->user->id,
            'tenant_id' => $this->tenant->id,
            'is_active' => true,
            'is_default' => true,
        ]);

        // 로그인 및 토큰 획득
        $this->loginAndGetToken();
    }

    protected function loginAndGetToken(): void
    {
        $response = $this->withHeaders([
            'X-API-KEY' => $this->apiKey,
            'Accept' => 'application/json',
        ])->postJson('/api/v1/login', [
            'user_id' => $this->user->user_id,
            'user_pwd' => 'password123',
        ]);

        $response->assertStatus(200);
        $this->token = $response->json('access_token');
    }

    protected function authenticatedRequest(string $method, string $uri, array $data = [])
    {
        return $this->withHeaders([
            'X-API-KEY' => $this->apiKey,
            'Authorization' => 'Bearer '.$this->token,
            'Accept' => 'application/json',
        ])->{$method.'Json'}($uri, $data);
    }

    // ==================== Business Number Check Tests ====================

    public function test_can_check_business_number(): void
    {
        $response = $this->authenticatedRequest('post', '/api/v1/companies/check', [
            'business_number' => '123-45-67890',
        ]);

        // 200 (검증 성공) 또는 다른 응답
        $this->assertContains($response->status(), [200, 400, 422]);
    }

    public function test_cannot_check_without_business_number(): void
    {
        $response = $this->authenticatedRequest('post', '/api/v1/companies/check', [
            // business_number 누락
        ]);

        $response->assertStatus(422);
    }

    public function test_cannot_check_with_invalid_business_number_format(): void
    {
        $response = $this->authenticatedRequest('post', '/api/v1/companies/check', [
            'business_number' => 'invalid',
        ]);

        $response->assertStatus(422);
    }

    // ==================== Company Request Tests ====================

    public function test_can_create_company_request(): void
    {
        $response = $this->authenticatedRequest('post', '/api/v1/companies/request', [
            'business_number' => '123-45-67890',
            'company_name' => 'New Test Company',
            'ceo_name' => 'Kim CEO',
            'address' => '서울시 강남구',
            'phone' => '02-1234-5678',
            'email' => 'company@example.com',
            'message' => '새 회사 추가 요청합니다.',
        ]);

        // 201 (생성 성공) 또는 200, 400 (검증 실패), 서비스 미구현 시 500
        $this->assertContains($response->status(), [200, 201, 400, 500]);
    }

    public function test_can_get_my_requests(): void
    {
        // 내 신청 생성
        CompanyRequest::create([
            'user_id' => $this->user->id,
            'business_number' => '111-22-33333',
            'company_name' => 'My Request Company',
            'status' => CompanyRequest::STATUS_PENDING,
        ]);

        $response = $this->authenticatedRequest('get', '/api/v1/companies/my-requests');

        $response->assertStatus(200)
            ->assertJsonStructure([
                'success',
                'message',
                'data',
            ]);
    }

    // ==================== Admin Request Management Tests ====================

    public function test_can_list_company_requests(): void
    {
        // 신청 생성
        CompanyRequest::create([
            'user_id' => $this->user->id,
            'business_number' => '222-33-44444',
            'company_name' => 'Request List Company',
            'status' => CompanyRequest::STATUS_PENDING,
        ]);

        $response = $this->authenticatedRequest('get', '/api/v1/companies/requests');

        $response->assertStatus(200)
            ->assertJsonStructure([
                'success',
                'message',
                'data',
            ]);
    }

    public function test_can_show_company_request(): void
    {
        $request = CompanyRequest::create([
            'user_id' => $this->user->id,
            'business_number' => '333-44-55555',
            'company_name' => 'Show Request Company',
            'status' => CompanyRequest::STATUS_PENDING,
        ]);

        $response = $this->authenticatedRequest('get', "/api/v1/companies/requests/{$request->id}");

        $response->assertStatus(200)
            ->assertJsonStructure([
                'success',
                'message',
                'data',
            ]);
    }

    public function test_can_approve_company_request(): void
    {
        $request = CompanyRequest::create([
            'user_id' => $this->user->id,
            'business_number' => '444-55-66666',
            'company_name' => 'Approve Test Company',
            'ceo_name' => 'Test CEO',
            'email' => 'approve-test@example.com',
            'status' => CompanyRequest::STATUS_PENDING,
        ]);

        $response = $this->authenticatedRequest('post', "/api/v1/companies/requests/{$request->id}/approve");

        // 200 (승인 성공) 또는 권한 관련 에러
        $this->assertContains($response->status(), [200, 403, 422]);
    }

    public function test_can_reject_company_request(): void
    {
        $request = CompanyRequest::create([
            'user_id' => $this->user->id,
            'business_number' => '555-66-77777',
            'company_name' => 'Reject Test Company',
            'status' => CompanyRequest::STATUS_PENDING,
        ]);

        $response = $this->authenticatedRequest('post', "/api/v1/companies/requests/{$request->id}/reject", [
            'reason' => '서류 미비로 반려합니다.',
        ]);

        // 200 (반려 성공) 또는 권한 관련 에러
        $this->assertContains($response->status(), [200, 403, 422]);
    }

    // ==================== Status Filter Tests ====================

    public function test_can_filter_requests_by_status(): void
    {
        // Pending 신청
        CompanyRequest::create([
            'user_id' => $this->user->id,
            'business_number' => '666-77-88888',
            'company_name' => 'Pending Company',
            'status' => CompanyRequest::STATUS_PENDING,
        ]);

        $response = $this->authenticatedRequest('get', '/api/v1/companies/requests?status=pending');

        $response->assertStatus(200);
    }

    // ==================== Validation Tests ====================

    public function test_cannot_create_request_without_required_fields(): void
    {
        $response = $this->authenticatedRequest('post', '/api/v1/companies/request', [
            // business_number, company_name 누락
        ]);

        $response->assertStatus(422);
    }

    public function test_cannot_approve_already_processed_request(): void
    {
        $request = CompanyRequest::create([
            'user_id' => $this->user->id,
            'business_number' => '777-88-99999',
            'company_name' => 'Already Approved Company',
            'status' => CompanyRequest::STATUS_APPROVED,
            'approved_by' => $this->user->id,
            'processed_at' => now(),
        ]);

        $response = $this->authenticatedRequest('post', "/api/v1/companies/requests/{$request->id}/approve");

        // 400 또는 422 (이미 처리된 신청)
        $this->assertContains($response->status(), [400, 422]);
    }

    // ==================== Authentication Tests ====================

    public function test_cannot_access_requests_without_authentication(): void
    {
        $response = $this->withHeaders([
            'X-API-KEY' => $this->apiKey,
            'Accept' => 'application/json',
        ])->getJson('/api/v1/companies/requests');

        $response->assertStatus(401);
    }

    public function test_cannot_create_request_without_authentication(): void
    {
        $response = $this->withHeaders([
            'X-API-KEY' => $this->apiKey,
            'Accept' => 'application/json',
        ])->postJson('/api/v1/companies/request', [
            'business_number' => '999-00-11111',
            'company_name' => 'Auth Test Company',
        ]);

        $response->assertStatus(401);
    }

    public function test_cannot_check_business_number_without_authentication(): void
    {
        $response = $this->withHeaders([
            'X-API-KEY' => $this->apiKey,
            'Accept' => 'application/json',
        ])->postJson('/api/v1/companies/check', [
            'business_number' => '123-45-67890',
        ]);

        $response->assertStatus(401);
    }
}
