import PocketBase from "pocketbase";

export interface PushSubscriptionRecord {
  id: string;
  player: string;
  endpoint: string;
  p256dh: string;
  auth: string;
  user_agent?: string;
  created: string;
  updated: string;
}

export interface PushSubscriptionInput {
  player: string;
  endpoint: string;
  p256dh: string;
  auth: string;
  user_agent?: string;
}

export const createPushService = (pb: PocketBase) => ({
  async listPushSubscriptionsByPlayer(
    playerId: string
  ): Promise<PushSubscriptionRecord[]> {
    return await pb
      .collection("push_subscriptions")
      .getFullList<PushSubscriptionRecord>({
        filter: `player = "${playerId}"`,
      });
  },

  async getPushSubscriptionByEndpoint(
    endpoint: string
  ): Promise<PushSubscriptionRecord | null> {
    try {
      return await pb
        .collection("push_subscriptions")
        .getFirstListItem<PushSubscriptionRecord>(
          `endpoint = "${endpoint}"`
        );
    } catch {
      return null;
    }
  },

  async upsertPushSubscription(
    data: PushSubscriptionInput
  ): Promise<PushSubscriptionRecord> {
    const existing = await this.getPushSubscriptionByEndpoint(data.endpoint);
    if (existing) {
      return await pb
        .collection("push_subscriptions")
        .update<PushSubscriptionRecord>(existing.id, data);
    }
    return await pb
      .collection("push_subscriptions")
      .create<PushSubscriptionRecord>(data);
  },

  async deletePushSubscriptionByEndpoint(endpoint: string): Promise<void> {
    const existing = await this.getPushSubscriptionByEndpoint(endpoint);
    if (existing) {
      await pb.collection("push_subscriptions").delete(existing.id);
    }
  },

  async deletePushSubscriptionById(id: string): Promise<void> {
    await pb.collection("push_subscriptions").delete(id);
  },
});
