<?php

namespace App\Services\Intune;

use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Models\ManagedEnvironment;
use App\Services\AssignmentBackupService;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;

class BackupService
{
    public function __construct(
        private readonly AuditLogger $auditLogger,
        private readonly VersionService $versionService,
        private readonly SnapshotValidator $snapshotValidator,
        private readonly PolicySnapshotService $snapshotService,
        private readonly AssignmentBackupService $assignmentBackupService,
        private readonly PolicyCaptureOrchestrator $captureOrchestrator,
        private readonly FoundationSnapshotService $foundationSnapshots,
    ) {}

    /**
     * Create a backup set with immutable snapshots for the provided policies.
     *
     * @param  array<int>  $policyIds
     */
    public function createBackupSet(
        ManagedEnvironment $tenant,
        array $policyIds,
        ?string $actorEmail = null,
        ?string $actorName = null,
        ?string $name = null,
        bool $includeAssignments = false,
        bool $includeScopeTags = false,
        bool $includeFoundations = false,
    ): BackupSet {
        $this->assertActiveTenant($tenant);

        $policies = Policy::query()
            ->where('managed_environment_id', $tenant->id)
            ->whereIn('id', $policyIds)
            ->currentBackupEligible()
            ->get();

        $backupSet = DB::transaction(function () use ($tenant, $policies, $actorEmail, $name, $includeAssignments, $includeScopeTags, $includeFoundations) {
            $backupSet = BackupSet::create([
                'managed_environment_id' => $tenant->id,
                'name' => $name ?? CarbonImmutable::now()->format('Y-m-d H:i:s').' backup',
                'created_by' => $actorEmail,
                'status' => 'running',
                'metadata' => [],
            ]);

            $failures = [];
            $itemsCreated = 0;

            foreach ($policies as $policy) {
                [$item, $failure] = $this->snapshotPolicy(
                    $tenant,
                    $backupSet,
                    $policy,
                    $actorEmail,
                    $includeAssignments,
                    $includeScopeTags
                );

                if ($failure !== null) {
                    $failures[] = $failure;

                    continue;
                }

                if ($item !== null) {
                    $itemsCreated++;
                }
            }

            if ($includeFoundations) {
                $foundationOutcome = $this->captureFoundations($tenant, $backupSet);
                $itemsCreated += $foundationOutcome['created'] + $foundationOutcome['restored'];
                $failures = array_merge($failures, $foundationOutcome['failures']);
            }

            $status = $this->resolveStatus($itemsCreated, $failures);

            $backupSet->update([
                'status' => $status,
                'item_count' => $itemsCreated,
                'completed_at' => CarbonImmutable::now(),
                'metadata' => ['failures' => $failures],
            ]);

            return $backupSet->refresh();
        });

        $this->auditLogger->log(
            tenant: $tenant,
            action: 'backup.created',
            context: [
                'metadata' => [
                    'backup_set_id' => $backupSet->id,
                    'item_count' => $backupSet->item_count,
                    'status' => $backupSet->status,
                ],
            ],
            actorEmail: $actorEmail,
            actorName: $actorName,
            resourceType: 'backup_set',
            resourceId: (string) $backupSet->id,
            status: $backupSet->status === 'completed' ? 'success' : 'partial'
        );

        // Log if assignments were included
        if ($includeAssignments) {
            $items = $backupSet->items;
            $assignmentCount = $items->sum(function ($item) {
                return $item->metadata['assignment_count'] ?? 0;
            });

            $this->auditLogger->log(
                tenant: $tenant,
                action: 'backup.assignments.included',
                context: [
                    'metadata' => [
                        'backup_set_id' => $backupSet->id,
                        'policy_count' => $backupSet->item_count,
                        'assignment_count' => $assignmentCount,
                    ],
                ],
                actorEmail: $actorEmail,
                actorName: $actorName,
                resourceType: 'backup_set',
                resourceId: (string) $backupSet->id,
                status: 'success'
            );
        }

        return $backupSet;
    }

    /**
     * Add snapshots for additional policies to an existing backup set.
     *
     * @param  array<int>  $policyIds
     */
    public function addPoliciesToSet(
        ManagedEnvironment $tenant,
        BackupSet $backupSet,
        array $policyIds,
        ?string $actorEmail = null,
        ?string $actorName = null,
        bool $includeAssignments = false,
        bool $includeScopeTags = false,
        bool $includeFoundations = false,
    ): BackupSet {
        $this->assertActiveTenant($tenant);

        if ($backupSet->trashed() || $backupSet->managed_environment_id !== $tenant->id) {
            throw new \RuntimeException('Backup set is archived or does not belong to the current tenant.');
        }

        $existingPolicyIds = $backupSet->items()->withTrashed()->pluck('policy_id')->filter()->all();

        // Separate into truly new policies and soft-deleted ones to restore
        $softDeletedItems = $backupSet->items()->onlyTrashed()->whereIn('policy_id', $policyIds)->get();
        $softDeletedPolicyIds = $softDeletedItems->pluck('policy_id')->all();

        // Restore soft-deleted items
        foreach ($softDeletedItems as $item) {
            $item->restore();
        }

        // Only create new items for policies that don't exist at all
        $policyIds = array_values(array_diff($policyIds, $existingPolicyIds));

        if (empty($policyIds) && $softDeletedItems->isEmpty()) {
            return $backupSet->refresh();
        }

        $policies = Policy::query()
            ->where('managed_environment_id', $tenant->id)
            ->whereIn('id', $policyIds)
            ->currentBackupEligible()
            ->get();

        $metadata = $backupSet->metadata ?? [];
        $failures = $metadata['failures'] ?? [];
        $itemsCreated = 0;

        foreach ($policies as $policy) {
            [$item, $failure] = $this->snapshotPolicy(
                $tenant,
                $backupSet,
                $policy,
                $actorEmail,
                $includeAssignments,
                $includeScopeTags
            );

            if ($failure !== null) {
                $failures[] = $failure;

                continue;
            }

            if ($item !== null) {
                $itemsCreated++;
            }
        }

        if ($includeFoundations) {
            $foundationOutcome = $this->captureFoundations($tenant, $backupSet);
            $itemsCreated += $foundationOutcome['created'] + $foundationOutcome['restored'];
            $failures = array_merge($failures, $foundationOutcome['failures']);
        }

        $status = $this->resolveStatus($itemsCreated, $failures);

        $backupSet->update([
            'status' => $status,
            'item_count' => $backupSet->items()->count(),
            'completed_at' => CarbonImmutable::now(),
            'metadata' => ['failures' => $failures],
        ]);

        $this->auditLogger->log(
            tenant: $tenant,
            action: 'backup.items_added',
            context: [
                'metadata' => [
                    'backup_set_id' => $backupSet->id,
                    'added_count' => $itemsCreated,
                    'restored_count' => $softDeletedItems->count(),
                    'status' => $status,
                ],
            ],
            actorEmail: $actorEmail,
            actorName: $actorName,
            resourceType: 'backup_set',
            resourceId: (string) $backupSet->id,
            status: $status === 'completed' ? 'success' : 'partial'
        );

        return $backupSet->refresh();
    }

    private function resolveStatus(int $itemsCreated, array $failures): string
    {
        return match (true) {
            $itemsCreated === 0 && count($failures) > 0 => 'failed',
            count($failures) > 0 => 'partial',
            default => 'completed',
        };
    }

    /**
     * @return array{0:?BackupItem,1:?array{policy_id:int,reason:string,status:int|string|null}}
     */
    private function snapshotPolicy(
        ManagedEnvironment $tenant,
        BackupSet $backupSet,
        Policy $policy,
        ?string $actorEmail = null,
        bool $includeAssignments = false,
        bool $includeScopeTags = false
    ): array {
        // Use orchestrator to capture policy + assignments into PolicyVersion first
        $captureResult = $this->captureOrchestrator->capture(
            policy: $policy,
            tenant: $tenant,
            includeAssignments: $includeAssignments,
            includeScopeTags: $includeScopeTags,
            createdBy: $actorEmail,
            metadata: [
                'source' => 'backup',
                'backup_set_id' => $backupSet->id,
            ]
        );

        // Check for capture failure
        if (isset($captureResult['failure'])) {
            return [null, $captureResult['failure']];
        }

        $version = $captureResult['version'];
        $captured = $captureResult['captured'];
        $payload = $captured['payload'];
        $metadata = $captured['metadata'] ?? [];
        $backupItem = $this->createBackupItemFromVersion(
            tenant: $tenant,
            backupSet: $backupSet,
            policy: $policy,
            version: $version,
            payload: is_array($payload) ? $payload : [],
            assignments: $captured['assignments'] ?? null,
            scopeTags: $captured['scope_tags'] ?? null,
            metadata: is_array($metadata) ? $metadata : [],
            warnings: $captured['warnings'] ?? [],
        );

        if ($includeAssignments) {
            $this->assignmentBackupService->recordFetchOperationRun(
                backupItem: $backupItem,
                tenant: $tenant,
                captureMetadata: is_array($metadata) ? $metadata : [],
            );
        }

        return [$backupItem, null];
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $metadata
     * @param  array<int, string>  $warnings
     * @param  array{ids:array<int, string>,names:array<int, string>}|null  $scopeTags
     */
    private function createBackupItemFromVersion(
        ManagedEnvironment $tenant,
        BackupSet $backupSet,
        Policy $policy,
        PolicyVersion $version,
        array $payload,
        ?array $assignments,
        ?array $scopeTags,
        array $metadata,
        array $warnings = [],
    ): BackupItem {
        $metadataWarnings = $warnings;

        $validation = $this->snapshotValidator->validate($payload);
        $metadataWarnings = array_merge($metadataWarnings, $validation['warnings']);

        $odataWarning = BackupItem::odataTypeWarning($payload, $policy->policy_type, $policy->platform);

        if ($odataWarning) {
            $metadataWarnings[] = $odataWarning;
        }

        if (! empty($metadataWarnings)) {
            $metadata['warnings'] = array_values(array_unique($metadataWarnings));
        }

        if (is_array($scopeTags)) {
            $metadata['scope_tag_ids'] = $scopeTags['ids'] ?? null;
            $metadata['scope_tag_names'] = $scopeTags['names'] ?? null;
        }

        return BackupItem::create([
            'managed_environment_id' => $tenant->id,
            'backup_set_id' => $backupSet->id,
            'policy_id' => $policy->id,
            'policy_version_id' => $version->id,
            'policy_identifier' => $policy->external_id,
            'policy_type' => $policy->policy_type,
            'platform' => $policy->platform,
            'payload' => $payload,
            'metadata' => $metadata,
            'assignments' => $assignments,
        ]);
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $metadata
     */
    private function createFoundationBackupItem(
        ManagedEnvironment $tenant,
        BackupSet $backupSet,
        string $foundationType,
        ?string $platform,
        string $sourceId,
        array $payload,
        array $metadata,
        ?Policy $policy = null,
        ?PolicyVersion $version = null,
    ): BackupItem {
        $warnings = is_array($metadata['warnings'] ?? null) ? $metadata['warnings'] : [];
        $validation = $this->snapshotValidator->validate($payload);
        $warnings = array_merge($warnings, $validation['warnings']);

        $odataWarning = BackupItem::odataTypeWarning($payload, $foundationType, $platform);
        if ($odataWarning !== null) {
            $warnings[] = $odataWarning;
        }

        if ($warnings !== []) {
            $metadata['warnings'] = array_values(array_unique($warnings));
        }

        return BackupItem::create([
            'managed_environment_id' => $tenant->id,
            'backup_set_id' => $backupSet->id,
            'policy_id' => $policy?->getKey(),
            'policy_version_id' => $version?->getKey(),
            'policy_identifier' => $sourceId,
            'policy_type' => $foundationType,
            'platform' => $platform,
            'payload' => $payload,
            'metadata' => $metadata,
        ]);
    }

    /**
     * @return array{created:int,restored:int,failures:array<int,array{foundation_type:string,reason:string,status:int|string|null}>}
     */
    private function captureFoundations(ManagedEnvironment $tenant, BackupSet $backupSet): array
    {
        $types = config('tenantpilot.foundation_types', []);
        $created = 0;
        $restored = 0;
        $failures = [];

        foreach ($types as $typeConfig) {
            $foundationType = $typeConfig['type'] ?? null;

            if (! is_string($foundationType) || $foundationType === '') {
                continue;
            }

            $result = $this->foundationSnapshots->fetchAll($tenant, $foundationType);
            $failures = array_merge($failures, $result['failures'] ?? []);

            foreach ($result['items'] as $snapshot) {
                $sourceId = $snapshot['source_id'] ?? null;

                if (! is_string($sourceId) || $sourceId === '') {
                    continue;
                }

                $existing = BackupItem::withTrashed()
                    ->where('backup_set_id', $backupSet->id)
                    ->where('policy_type', $foundationType)
                    ->where('policy_identifier', $sourceId)
                    ->first();

                if ($existing) {
                    if ($existing->trashed()) {
                        $existing->restore();
                        $restored++;
                    }

                    continue;
                }

                $payload = is_array($snapshot['payload'] ?? null) ? $snapshot['payload'] : [];
                $metadata = is_array($snapshot['metadata'] ?? null) ? $snapshot['metadata'] : [];
                $platform = is_string($typeConfig['platform'] ?? null) ? $typeConfig['platform'] : null;

                if ($this->supportsFoundationVersioning($foundationType)) {
                    $policy = $this->resolveFoundationPolicy(
                        tenant: $tenant,
                        foundationType: $foundationType,
                        sourceId: $sourceId,
                        platform: $platform,
                        payload: $payload,
                        metadata: $metadata,
                    );

                    $version = $this->versionService->captureFoundationVersion(
                        policy: $policy,
                        payload: $payload,
                        metadata: array_merge(
                            $metadata,
                            [
                                'foundation_type' => $foundationType,
                                'source' => 'backup_foundation',
                            ],
                        ),
                    );

                    $this->createFoundationBackupItem(
                        tenant: $tenant,
                        backupSet: $backupSet,
                        foundationType: $foundationType,
                        platform: $platform,
                        sourceId: $sourceId,
                        payload: $payload,
                        metadata: $metadata,
                        policy: $policy,
                        version: $version,
                    );
                } else {
                    $this->createFoundationBackupItem(
                        tenant: $tenant,
                        backupSet: $backupSet,
                        foundationType: $foundationType,
                        platform: $platform,
                        sourceId: $sourceId,
                        payload: $payload,
                        metadata: $metadata,
                    );
                }

                $created++;
            }
        }

        return [
            'created' => $created,
            'restored' => $restored,
            'failures' => $failures,
        ];
    }

    private function supportsFoundationVersioning(string $foundationType): bool
    {
        return in_array($foundationType, ['intuneRoleDefinition', 'intuneRoleAssignment'], true);
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $metadata
     */
    private function resolveFoundationPolicy(
        ManagedEnvironment $tenant,
        string $foundationType,
        string $sourceId,
        ?string $platform,
        array $payload,
        array $metadata,
    ): Policy {
        $displayName = $metadata['displayName']
            ?? $metadata['display_name']
            ?? $payload['displayName']
            ?? $payload['name']
            ?? $sourceId;

        $policy = Policy::query()->firstOrNew([
            'managed_environment_id' => $tenant->getKey(),
            'external_id' => $sourceId,
            'policy_type' => $foundationType,
        ]);

        $existingMetadata = is_array($policy->metadata) ? $policy->metadata : [];

        $policy->fill([
            'platform' => $platform,
            'display_name' => is_string($displayName) && $displayName !== '' ? $displayName : $sourceId,
            'last_synced_at' => null,
            'metadata' => array_merge(
                $existingMetadata,
                [
                    'foundation_anchor' => true,
                    'foundation_type' => $foundationType,
                    'capture_mode' => 'immutable_backup',
                ],
            ),
        ]);
        $policy->save();

        return $policy;
    }

    private function assertActiveTenant(ManagedEnvironment $tenant): void
    {
        if (! $tenant->isActive()) {
            throw new \RuntimeException('ManagedEnvironment is archived or inactive.');
        }
    }
}
