import { db } from '../db/client.js';
import type { IntegrationTokenRow, IntegrationTokenScope } from '../types.js';

export const listIntegrationTokens = async (userId: string, workspaceId: number) => {
  const result = await db.query<IntegrationTokenRow>(
    `SELECT id, user_id, workspace_id, name, token_hash, token_prefix, scope, last_used_at::text, expires_at::text, revoked_at::text, created_at
     FROM integration_tokens
     WHERE user_id = $1
       AND workspace_id = $2
       AND revoked_at IS NULL
     ORDER BY created_at DESC`,
    [userId, workspaceId],
  );

  return result.rows;
};

export const createIntegrationTokenRecord = async ({
  userId,
  workspaceId,
  name,
  tokenHash,
  tokenPrefix,
  scope,
  expiresAt,
}: {
  userId: string;
  workspaceId: number;
  name: string;
  tokenHash: string;
  tokenPrefix: string;
  scope: IntegrationTokenScope;
  expiresAt: string | null;
}) => {
  const result = await db.query<IntegrationTokenRow>(
    `INSERT INTO integration_tokens (user_id, workspace_id, name, token_hash, token_prefix, scope, expires_at)
     VALUES ($1, $2, $3, $4, $5, $6, $7)
     RETURNING id, user_id, workspace_id, name, token_hash, token_prefix, scope, last_used_at::text, expires_at::text, revoked_at::text, created_at`,
    [userId, workspaceId, name, tokenHash, tokenPrefix, scope, expiresAt],
  );

  return result.rows[0] ?? null;
};

export const revokeIntegrationToken = async (tokenId: string, userId: string, workspaceId: number) => {
  const result = await db.query<{ id: string }>(
    `UPDATE integration_tokens
     SET revoked_at = CURRENT_TIMESTAMP
     WHERE id = $1
       AND user_id = $2
       AND workspace_id = $3
       AND revoked_at IS NULL
     RETURNING id`,
    [tokenId, userId, workspaceId],
  );

  return Boolean(result.rowCount);
};
