import * as cdk from '@aws-cdk/core';
import { FilterPattern, LogGroup, RetentionDays, SubscriptionFilter } from '@aws-cdk/aws-logs';
import { KinesisDestination } from '@aws-cdk/aws-logs-destinations';
import { Stream, StreamEncryption } from '@aws-cdk/aws-kinesis';
import { KinesisEventSource } from '@aws-cdk/aws-lambda-event-sources';
import { Code, Function, Runtime, StartingPosition } from '@aws-cdk/aws-lambda';
import { join } from "path";
import { ManagedPolicy, Role, ServicePrincipal } from "@aws-cdk/aws-iam";

export class CdkStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const logGroup = LogGroup.fromLogGroupName(this, "LambdaLogGroup", "/aws/lambda/TestLogProducer");

    const stream = new Stream(this, "TestStream", {
      streamName: "EventIngestion",
      encryption: StreamEncryption.UNENCRYPTED,
    });
    const destination = new KinesisDestination(stream);
    const filter = new SubscriptionFilter(this, 'TestSubscription', {
      logGroup,
      filterPattern: FilterPattern.allTerms("Operation"),
      destination,
    });

    const kinesisEventSource = new KinesisEventSource(stream, {
      startingPosition: StartingPosition.LATEST,
    });

    const role = new Role(this, "ProcessLogEventsRoll", {
      assumedBy: new ServicePrincipal("lambda.amazonaws.com")
    })
    role.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"));

    const processorFunction = new Function(this, "ProcessLogEvents", {
      runtime: Runtime.GO_1_X,
      handler: "ingest-log-events",
      code: Code.fromAsset(join(process.cwd(), "../api/build/ingest-log-events/")),
      role,
      logRetention: RetentionDays.FIVE_DAYS,
    });
    stream.grantRead(role);

    processorFunction.addEventSource(kinesisEventSource);

  }
}
