import { requireUserSession } from '../../utils/auth.ts'
import { useDB } from '../../utils/database.ts'
import { account } from '../../database/schema/auth.ts'
import { eq } from 'drizzle-orm'
import { handleApiError, createSuccessResponse } from '../../utils/errors'

interface AccountResponse {
  id: string
  providerId: string
  accountId: string
  createdAt: Date
}

export default defineEventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)

    const db = useDB()

    // Fetch all OAuth accounts for the logged-in user
    const accounts = await db
      .select({
        id: account.id,
        providerId: account.providerId,
        accountId: account.accountId,
        createdAt: account.createdAt
      })
      .from(account)
      .where(eq(account.userId, session.user.id))

    return createSuccessResponse<AccountResponse[]>(accounts, 'Accounts retrieved successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
