import { DynamoDBClient, GetItemCommand, PutItemCommand } from "@aws-sdk/client-dynamodb";
import type { PrSnapshot } from "./daily-report.js";

const PK = "open-prs";

export class DailyReportStore {
  private client: DynamoDBClient;

  constructor(private readonly tableName: string) {
    this.client = new DynamoDBClient({});
  }

  async loadOpenPrs(): Promise<Map<string, PrSnapshot>> {
    const { Item } = await this.client.send(
      new GetItemCommand({
        TableName: this.tableName,
        Key: { pk: { S: PK } },
      }),
    );

    if (!Item?.data?.S) return new Map();

    const entries: [string, PrSnapshot][] = JSON.parse(Item.data.S);
    return new Map(entries);
  }

  async saveOpenPrs(prs: Map<string, PrSnapshot>): Promise<void> {
    await this.client.send(
      new PutItemCommand({
        TableName: this.tableName,
        Item: {
          pk: { S: PK },
          data: { S: JSON.stringify([...prs.entries()]) },
        },
      }),
    );
  }
}
