import Foundation
import TuistCore

/// Mapper that generates a new scheme `ProjectName-Project` that includes all targets
/// From a given workspace
public final class AutogeneratedProjectSchemeWorkspaceMapper: WorkspaceMapping {
    public init() {}

    public func map(workspace: WorkspaceWithProjects) throws -> (WorkspaceWithProjects, [SideEffectDescriptor]) {
        guard let project = workspace.projects.first else { return (workspace, []) }

        let (targets, testableTargets): ([TargetReference], [TestableTarget]) = workspace.projects.reduce(([], [])) { result, project in
            let targets = project.targets
                .filter { !$0.product.testsBundle }
                .map { TargetReference(projectPath: project.path, name: $0.name) }
            let testableTargets = project.targets
                .filter(\.product.testsBundle)
                .map { TargetReference(projectPath: project.path, name: $0.name) }
                .map { TestableTarget(target: $0) }

            return (result.0 + targets, result.1 + testableTargets)
        }

        let scheme = Scheme(
            name: "\(workspace.workspace.name)-Project",
            shared: true,
            buildAction: BuildAction(targets: targets),
            testAction: TestAction(
                targets: testableTargets,
                arguments: nil,
                configurationName: project.defaultDebugBuildConfigurationName,
                coverage: false,
                codeCoverageTargets: [],
                preActions: [],
                postActions: [],
                diagnosticsOptions: Set()
            )
        )

        var workspace = workspace
        workspace.workspace.schemes.append(scheme)
        return (workspace, [])
    }
}
