<?php

namespace App\Core\Services;

use App\Enums\RoleEnum;
use App\Models\Permission;
use App\Models\Role;

/**
 * Permission Service
 * Handles permission assignment and synchronization
 */
class PermissionService
{
    public function __construct(
        private PluginService $pluginService
    ) {}

    /**
     * Permission groups
     */
    public const INVOICE_PERMISSIONS = [
        'view_invoices',
        'create_invoices',
        'edit_invoices',
        'delete_invoices',
        'pay_invoices',
    ];

    public const USER_PERMISSIONS = [
        'view_users',
        'create_users',
        'edit_users',
        'delete_users',
        'manage_users',
    ];

    public const SETTINGS_PERMISSIONS = [
        'view_settings',
        'manage_settings',
        'manage_company',
        'manage_localization',
    ];

    public const SAAS_PERMISSIONS = [
        'manage_saas',
        'manage_subscriptions',
        'manage_tenants',
        'manage_plans',
    ];

    public const SALES_PERMISSIONS = [
        'view_reports',
        'view_sales',
        'manage_customers',
    ];

    /** Smart billing reminders & notification templates */
    public const REMINDER_PERMISSIONS = [
        'manage_reminders',
        'manage_email_templates',
        'send_manual_reminders',
        'view_reminder_logs',
    ];

    /**
     * Get all permissions
     */
    public function getAllPermissions(): array
    {
        return array_merge(
            self::INVOICE_PERMISSIONS,
            self::USER_PERMISSIONS,
            self::SETTINGS_PERMISSIONS,
            self::SAAS_PERMISSIONS,
            self::SALES_PERMISSIONS,
            self::REMINDER_PERMISSIONS
        );
    }

    /**
     * Sync all permissions to database
     */
    public function syncPermissions(): void
    {
        $allPermissions = $this->getAllPermissions();

        foreach ($allPermissions as $permissionSlug) {
            Permission::firstOrCreate(
                ['slug' => $permissionSlug],
                [
                    'name' => $this->formatPermissionName($permissionSlug),
                    'description' => $this->getPermissionDescription($permissionSlug),
                ]
            );
        }
    }

    /**
     * Auto-assign default permissions based on SaaS plugin status
     */
    public function assignDefaultPermissions(): void
    {
        $isSaaSActive = $this->pluginService->isSaaSActive();

        if ($isSaaSActive) {
            $this->assignPermissionsForSaaSActive();
        } else {
            $this->assignPermissionsForSaaSInactive();
        }
    }

    /**
     * Assign permissions when SaaS is active
     */
    private function assignPermissionsForSaaSActive(): void
    {
        // SUPER_ADMIN - All permissions
        $superAdminRole = Role::where('slug', RoleEnum::SUPER_ADMIN->value)->first();
        if ($superAdminRole) {
            $allPermissions = Permission::whereIn('slug', $this->getAllPermissions())->pluck('id');
            $superAdminRole->permissions()->sync($allPermissions);
        }

        // ADMINISTRATION - Limited permissions
        $adminRole = Role::where('slug', RoleEnum::ADMINISTRATION->value)->first();
        if ($adminRole) {
            $adminPermissions = array_merge(
                self::INVOICE_PERMISSIONS,
                self::USER_PERMISSIONS,
                self::SALES_PERMISSIONS,
                self::REMINDER_PERMISSIONS
            );
            $permissionIds = Permission::whereIn('slug', $adminPermissions)->pluck('id');
            $adminRole->permissions()->sync($permissionIds);
        }

        // SALES_MANAGER - Sales and invoice permissions
        $salesRole = Role::where('slug', RoleEnum::SALES_MANAGER->value)->first();
        if ($salesRole) {
            $salesPermissions = array_merge(
                ['view_invoices', 'create_invoices', 'edit_invoices'],
                self::SALES_PERMISSIONS
            );
            $permissionIds = Permission::whereIn('slug', $salesPermissions)->pluck('id');
            $salesRole->permissions()->sync($permissionIds);
        }

        // CUSTOMER - Only own invoice permissions
        $customerRole = Role::where('slug', RoleEnum::CUSTOMER->value)->first();
        if ($customerRole) {
            $customerPermissions = ['view_invoices', 'pay_invoices'];
            $permissionIds = Permission::whereIn('slug', $customerPermissions)->pluck('id');
            $customerRole->permissions()->sync($permissionIds);
        }
    }

    /**
     * Assign permissions when SaaS is inactive
     */
    private function assignPermissionsForSaaSInactive(): void
    {
        // ADMINISTRATION - All permissions (except SaaS)
        $adminRole = Role::where('slug', RoleEnum::ADMINISTRATION->value)->first();
        if ($adminRole) {
            $adminPermissions = array_merge(
                self::INVOICE_PERMISSIONS,
                self::USER_PERMISSIONS,
                self::SETTINGS_PERMISSIONS,
                self::SALES_PERMISSIONS,
                self::REMINDER_PERMISSIONS
            );
            $permissionIds = Permission::whereIn('slug', $adminPermissions)->pluck('id');
            $adminRole->permissions()->sync($permissionIds);
        }

        // SUPER_ADMIN - Same as administration (SaaS permissions hidden)
        $superAdminRole = Role::where('slug', RoleEnum::SUPER_ADMIN->value)->first();
        if ($superAdminRole) {
            $adminPermissions = array_merge(
                self::INVOICE_PERMISSIONS,
                self::USER_PERMISSIONS,
                self::SETTINGS_PERMISSIONS,
                self::SALES_PERMISSIONS,
                self::REMINDER_PERMISSIONS
            );
            $permissionIds = Permission::whereIn('slug', $adminPermissions)->pluck('id');
            $superAdminRole->permissions()->sync($permissionIds);
        }

        // SALES_MANAGER - Sales and invoice permissions
        $salesRole = Role::where('slug', RoleEnum::SALES_MANAGER->value)->first();
        if ($salesRole) {
            $salesPermissions = array_merge(
                ['view_invoices', 'create_invoices', 'edit_invoices'],
                self::SALES_PERMISSIONS
            );
            $permissionIds = Permission::whereIn('slug', $salesPermissions)->pluck('id');
            $salesRole->permissions()->sync($permissionIds);
        }

        // CUSTOMER - Only own invoice permissions
        $customerRole = Role::where('slug', RoleEnum::CUSTOMER->value)->first();
        if ($customerRole) {
            $customerPermissions = ['view_invoices', 'pay_invoices'];
            $permissionIds = Permission::whereIn('slug', $customerPermissions)->pluck('id');
            $customerRole->permissions()->sync($permissionIds);
        }
    }

    /**
     * Format permission name for display
     */
    private function formatPermissionName(string $slug): string
    {
        return ucwords(str_replace('_', ' ', $slug));
    }

    /**
     * Get permission description
     */
    private function getPermissionDescription(string $slug): string
    {
        $descriptions = [
            'view_invoices' => 'View invoices',
            'create_invoices' => 'Create new invoices',
            'edit_invoices' => 'Edit existing invoices',
            'delete_invoices' => 'Delete invoices',
            'pay_invoices' => 'Pay invoices',
            'view_users' => 'View user list',
            'create_users' => 'Create new users',
            'edit_users' => 'Edit user information',
            'delete_users' => 'Delete users',
            'manage_users' => 'Full user management',
            'view_settings' => 'View system settings',
            'manage_settings' => 'Manage system settings',
            'manage_company' => 'Manage company details',
            'manage_localization' => 'Manage localization settings',
            'manage_saas' => 'Manage SaaS configuration',
            'manage_subscriptions' => 'Manage subscriptions',
            'manage_tenants' => 'Manage tenants',
            'manage_plans' => 'Manage subscription plans',
            'view_reports' => 'View reports',
            'view_sales' => 'View sales data',
            'manage_customers' => 'Manage customers',
            'manage_reminders' => 'Configure billing reminder automation',
            'manage_email_templates' => 'Edit billing email templates',
            'send_manual_reminders' => 'Send manual invoice/quotation reminders',
            'view_reminder_logs' => 'View reminder & email delivery logs',
        ];

        return $descriptions[$slug] ?? ucwords(str_replace('_', ' ', $slug));
    }
}
