<?php

namespace App\Services;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\User;
use App\Tenancy\TenantManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

/**
 * Bootstraps a brand new tenant: creates the Company row, seeds default
 * roles + admin user, and (if Coolify is configured) adds the new
 * subdomain to the AutoCRM application's FQDN list and triggers redeploy.
 *
 * Returns plain credentials so the central admin can copy/email them.
 */
class CompanyProvisioner
{
    public function __construct(
        protected TenantManager $tenants,
        protected PermissionRegistrar $permissions,
        protected CoolifyClient $coolify,
    ) {}

    /**
     * @return array{company: Company, admin_email: string, admin_password: string, deploy_triggered: bool}
     */
    public function provision(array $data): array
    {
        $defaults = [
            'plan_id' => Plan::where('slug', 'free')->value('id'),
            'status' => 'trial',
            'trial_ends_at' => now()->addDays(14),
            'settings' => [
                'currency' => 'MDL',
                'language' => 'ro',
                'theme_color' => '#3B82F6',
                'labor_rate' => 400,
            ],
        ];

        return DB::transaction(function () use ($data, $defaults) {
            $company = Company::create(array_merge($defaults, [
                'slug' => $data['slug'],
                'name' => $data['name'],
                'display_name' => $data['display_name'] ?? $data['name'],
                'city' => $data['city'] ?? null,
                'phone' => $data['phone'] ?? null,
                'email' => $data['email'] ?? null,
                'contact_name' => $data['contact_name'] ?? null,
            ]));

            // Activate tenant context to seed roles + user with company_id auto-fill.
            $this->tenants->setCurrent($company);
            $this->permissions->setPermissionsTeamId($company->id);

            // Seed full RBAC catalog: 7 roles + 51 permissions + matrix per TZ.
            app(\App\Services\RbacSeeder::class)->seedTenantRoles($company->id);

            // Admin user.
            $adminEmail = $data['admin_email'] ?? "admin@{$company->slug}.local";
            $plainPassword = $data['admin_password'] ?? Str::password(10, true, true, false);
            $admin = User::create([
                'company_id' => $company->id,
                'name' => $data['admin_name'] ?? 'Administrator',
                'email' => $adminEmail,
                'password' => Hash::make($plainPassword),
                'role' => 'admin',
                'status' => 'active',
                'locale' => 'ro',
                'email_verified_at' => now(),
            ]);
            $admin->syncRoles(['admin']);

            $this->tenants->clear();

            // Add subdomain to Coolify FQDN list + trigger redeploy.
            $deployTriggered = false;
            $coolifyMessage = null;
            $appUuid = (string) config('services.coolify.app_uuid');

            if (! $this->coolify->isConfigured()) {
                $coolifyMessage = 'Coolify API nu e configurat (lipsesc env vars).';
            } elseif ($appUuid === '') {
                $coolifyMessage = 'COOLIFY_APP_UUID lipsește.';
            } else {
                $url = $company->url('');
                $url = rtrim($url, '/') . ':8000';
                if ($this->coolify->addDomain($appUuid, $url)) {
                    if ($this->coolify->deploy($appUuid, true)) {
                        $deployTriggered = true;
                        $coolifyMessage = 'OK';
                    } else {
                        $coolifyMessage = 'Domain adăugat dar redeploy a eșuat.';
                    }
                } else {
                    $coolifyMessage = 'addDomain Coolify eșuat (vezi log).';
                }
            }

            return [
                'company' => $company->fresh(),
                'admin_email' => $adminEmail,
                'admin_password' => $plainPassword,
                'deploy_triggered' => $deployTriggered,
                'coolify_message' => $coolifyMessage,
            ];
        });
    }

    public function suspend(Company $company): void
    {
        $company->update(['status' => 'suspended']);
    }

    public function reactivate(Company $company): void
    {
        $company->update(['status' => 'active']);
    }

    public function archive(Company $company): void
    {
        $company->update(['status' => 'archived']);
        $company->delete(); // soft-delete
    }
}
