import { CreateTableCommand, DynamoDBClient, KeyType, PutItemCommand, ScalarAttributeType } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
import { DoorAlias, DoorAliasEntity, DoorAliasSchema, getDoorAliasID } from "../schema/DoorAlias";
import { DoorConfig, getDoorConfigID, ONBOARDING_DOOR_NAME, ONBOARDING_DOOR_PIN } from "../schema/DoorConfig";

import DynamoDbLocal from "dynamodb-local";
import { sleep } from "bun";

console.log("starting local DDB");

const localDdb = await DynamoDbLocal.launch(5000, null, [], true, true);

process.on("SIGINT", async code => {
  console.log("exiting DDB local");
  await DynamoDbLocal.stopChild(localDdb);
});

// wait 5s so we are available
await sleep(5_000);

// seed ddb
const client = new DynamoDBClient({
  endpoint: 'http://localhost:5000',
});

const tableName = "doorman";

const createTableCommand = new CreateTableCommand({
  TableName: tableName,
  KeySchema: [
    { AttributeName: 'PK', KeyType: KeyType.HASH },
    { AttributeName: 'SK', KeyType: KeyType.RANGE }
  ],
  AttributeDefinitions: [
    { AttributeName: 'PK', AttributeType: ScalarAttributeType.S },
    { AttributeName: 'SK', AttributeType: ScalarAttributeType.S }
  ],
  ProvisionedThroughput: {
    ReadCapacityUnits: 5,
    WriteCapacityUnits: 5
  },
});

try {
  await client.send(createTableCommand);
} catch (e) {
  console.error("failed creating table", e);
}

const document = DynamoDBDocument.from(client, {
  marshallOptions: {
    removeUndefinedValues: true,
  }
});

const testDoorBuzzer = "6133163433";
const testDoorName = "test";
const testDoorPin = "1234";

const doorAlias: DoorAlias = {
  PK: testDoorBuzzer,
  SK: "alias",
  name: testDoorName,
};

const doorConfig: DoorConfig = {
  PK: "door-test",
  SK: "config",
  buzzer: testDoorBuzzer,
  pressKey: "4",
  // discordUsers: ["245290492760162304"],
  discordUsers: [],
  fallbackNumbers: ["1231231234"],
  pin: testDoorPin,
  buzzerCode: testDoorPin,
  timeout: 60,
  greeting: "test door",
};

// for onboarding mode
const onboardingDoorConfig: DoorConfig = {
  PK: "door-" + ONBOARDING_DOOR_NAME,
  SK: "config",
  buzzer: "nil",
  pressKey: "nil",
  discordUsers: [],
  fallbackNumbers: [],
  pin: ONBOARDING_DOOR_PIN,
  buzzerCode: "nil",
  timeout: 15 * 60,
  greeting: "INTERNAL USE - for onboarding new door",
};

try {
  await document.put({
    TableName: tableName,
    Item: doorConfig,
  });

  await document.put({
    TableName: tableName,
    Item: doorAlias,
  });

  await document.put({
    TableName: tableName,
    Item: onboardingDoorConfig,
  });

} catch (e) {
  console.error("failed seeding table", e);
}
