<?php

namespace Tests\Feature;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\Client;
use App\Models\Tenant\OnlineOrder;
use App\Models\Tenant\Part;
use App\Models\Tenant\ShopCustomer;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class ShopAccountTest extends TestCase
{
    use RefreshDatabase;

    public function test_register_creates_customer_and_logs_in(): void
    {
        $this->makeShopCompany('reg');

        $resp = $this->post('http://reg.service.mir.md/shop/register', [
            'name' => 'Ion Pop',
            'phone' => '+37369123456',
            'email' => 'ion@example.com',
            'password' => 'secret123',
            'password_confirmation' => 'secret123',
        ]);

        $resp->assertRedirect('/shop/account');

        $customer = ShopCustomer::where('phone', '+37369123456')->first();
        $this->assertNotNull($customer);
        $this->assertEquals('Ion Pop', $customer->name);
        $this->assertTrue(Hash::check('secret123', $customer->password));
        $this->assertTrue(Auth::guard('shop')->check());
    }

    public function test_register_auto_links_existing_client_by_phone(): void
    {
        $this->makeShopCompany('link');
        $client = Client::create([
            'name' => 'Existing', 'phone' => '+37369999999',
            'type' => 'individual', 'status' => 'active',
        ]);

        $this->post('http://link.service.mir.md/shop/register', [
            'name' => 'Existing', 'phone' => '+37369999999',
            'password' => 'pw1234', 'password_confirmation' => 'pw1234',
        ])->assertRedirect();

        $cust = ShopCustomer::first();
        $this->assertEquals($client->id, $cust->client_id);
    }

    public function test_register_rejects_duplicate_phone(): void
    {
        $this->makeShopCompany('dup');
        ShopCustomer::create([
            'name' => 'X', 'phone' => '+37377777777', 'password' => Hash::make('pw'),
        ]);

        $this->post('http://dup.service.mir.md/shop/register', [
            'name' => 'Y', 'phone' => '+37377777777',
            'password' => 'pw1234', 'password_confirmation' => 'pw1234',
        ])->assertSessionHasErrors('phone');

        $this->assertEquals(1, ShopCustomer::count());
    }

    public function test_login_validates_credentials(): void
    {
        $this->makeShopCompany('lg');
        ShopCustomer::create([
            'name' => 'L', 'phone' => '+37360123456',
            'password' => Hash::make('correct'),
        ]);

        $this->post('http://lg.service.mir.md/shop/login', [
            'phone' => '+37360123456', 'password' => 'wrong',
        ])->assertSessionHasErrors();
        $this->assertFalse(Auth::guard('shop')->check());

        $this->post('http://lg.service.mir.md/shop/login', [
            'phone' => '+37360123456', 'password' => 'correct',
        ])->assertRedirect();
        $this->assertTrue(Auth::guard('shop')->check());
    }

    public function test_account_page_requires_auth(): void
    {
        $this->makeShopCompany('acc');
        $this->get('http://acc.service.mir.md/shop/account')->assertRedirect('/shop/login');
    }

    public function test_account_page_lists_only_my_orders(): void
    {
        $ctx = $this->makeShopCompany('myorders');
        $part = Part::create(['name' => 'X', 'sell_price' => 100, 'qty' => 5, 'unit' => 'buc',
            'is_active' => true, 'is_published' => true]);

        $me = ShopCustomer::create([
            'name' => 'Me', 'phone' => '+37300000001',
            'password' => Hash::make('pw'),
        ]);
        $other = ShopCustomer::create([
            'name' => 'Other', 'phone' => '+37300000002',
            'password' => Hash::make('pw'),
        ]);

        $myOrder = OnlineOrder::create([
            'number' => OnlineOrder::generateNumber($ctx['company']->id),
            'shop_customer_id' => $me->id,
            'customer_name' => 'Me', 'customer_phone' => '+37300000001',
            'delivery_method' => 'pickup', 'status' => 'new',
        ]);
        OnlineOrder::create([
            'number' => OnlineOrder::generateNumber($ctx['company']->id),
            'shop_customer_id' => $other->id,
            'customer_name' => 'Other', 'customer_phone' => '+37300000002',
            'delivery_method' => 'pickup', 'status' => 'new',
        ]);

        Auth::guard('shop')->login($me);
        $resp = $this->get('http://myorders.service.mir.md/shop/account');
        $resp->assertOk();
        $resp->assertSee('#' . $myOrder->number);
        $resp->assertSee('Comenzile mele (1)');
    }

    public function test_checkout_attaches_shop_customer_id_when_logged_in(): void
    {
        $ctx = $this->makeShopCompany('co');
        $part = Part::create(['name' => 'Plăcuțe', 'sell_price' => 250, 'qty' => 5,
            'unit' => 'buc', 'is_active' => true, 'is_published' => true]);

        $customer = ShopCustomer::create([
            'name' => 'CO User', 'phone' => '+37345555555',
            'password' => Hash::make('pw'),
        ]);
        Auth::guard('shop')->login($customer);

        $base = 'http://co.service.mir.md/shop';
        $this->post("$base/part/{$part->id}/add", ['qty' => 1])->assertRedirect();

        $this->post("$base/checkout", [
            'customer_name' => $customer->name,
            'customer_phone' => $customer->phone,
            'delivery_method' => 'pickup',
        ])->assertRedirect();

        $order = OnlineOrder::first();
        $this->assertEquals($customer->id, $order->shop_customer_id);
    }

    public function test_customers_isolated_per_tenant(): void
    {
        $this->makeShopCompany('a');
        ShopCustomer::create([
            'name' => 'A Cust', 'phone' => '+37311111111',
            'password' => Hash::make('pw'),
        ]);

        $this->makeShopCompany('b');
        $this->assertEquals(0, ShopCustomer::count());
    }

    private function makeShopCompany(string $slug): array
    {
        $plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
        $company = Company::create([
            'plan_id' => $plan->id, 'slug' => $slug,
            'name' => ucfirst($slug), 'status' => 'active',
            'settings' => ['shop' => ['enabled' => true, 'delivery_methods' => ['pickup']]],
        ]);
        app(TenantManager::class)->setCurrent($company);
        return compact('company');
    }
}
