import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { credentialSet, credentialSetMember, member, organization, user } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { generateId } from '@sim/utils/id'
import { and, count, desc, eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import {
  createCredentialSetContract,
  listCredentialSetsQuerySchema,
} from '@/lib/api/contracts/credential-sets'
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { hasCredentialSetsAccess } from '@/lib/billing'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'

const logger = createLogger('CredentialSets')

export const GET = withRouteHandler(async (req: Request) => {
  const session = await getSession()

  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Check plan access (team/enterprise) or env var override
  const hasAccess = await hasCredentialSetsAccess(session.user.id)
  if (!hasAccess) {
    return NextResponse.json(
      { error: 'Credential sets require a Team or Enterprise plan' },
      { status: 403 }
    )
  }

  const { searchParams } = new URL(req.url)
  const validation = listCredentialSetsQuerySchema.safeParse({
    organizationId: searchParams.get('organizationId') ?? '',
  })

  if (!validation.success) {
    return NextResponse.json(
      { error: getValidationErrorMessage(validation.error) },
      { status: 400 }
    )
  }

  const { organizationId } = validation.data

  const membership = await db
    .select({ id: member.id, role: member.role })
    .from(member)
    .where(and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)))
    .limit(1)

  if (membership.length === 0) {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  }

  const sets = await db
    .select({
      id: credentialSet.id,
      name: credentialSet.name,
      description: credentialSet.description,
      providerId: credentialSet.providerId,
      createdBy: credentialSet.createdBy,
      createdAt: credentialSet.createdAt,
      updatedAt: credentialSet.updatedAt,
      creatorName: user.name,
      creatorEmail: user.email,
    })
    .from(credentialSet)
    .leftJoin(user, eq(credentialSet.createdBy, user.id))
    .where(eq(credentialSet.organizationId, organizationId))
    .orderBy(desc(credentialSet.createdAt))

  const setsWithCounts = await Promise.all(
    sets.map(async (set) => {
      const [memberCount] = await db
        .select({ count: count() })
        .from(credentialSetMember)
        .where(
          and(
            eq(credentialSetMember.credentialSetId, set.id),
            eq(credentialSetMember.status, 'active')
          )
        )

      return {
        ...set,
        memberCount: memberCount?.count ?? 0,
      }
    })
  )

  return NextResponse.json({ credentialSets: setsWithCounts })
})

export const POST = withRouteHandler(async (req: NextRequest) => {
  const session = await getSession()

  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Check plan access (team/enterprise) or env var override
  const hasAccess = await hasCredentialSetsAccess(session.user.id)
  if (!hasAccess) {
    return NextResponse.json(
      { error: 'Credential sets require a Team or Enterprise plan' },
      { status: 403 }
    )
  }

  try {
    const parsed = await parseRequest(
      createCredentialSetContract,
      req,
      {},
      {
        validationErrorResponse: (error) =>
          NextResponse.json({ error: getValidationErrorMessage(error) }, { status: 400 }),
      }
    )
    if (!parsed.success) return parsed.response

    const { organizationId, name, description, providerId } = parsed.data.body

    const membership = await db
      .select({ id: member.id, role: member.role })
      .from(member)
      .where(and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)))
      .limit(1)

    const role = membership[0]?.role
    if (membership.length === 0 || (role !== 'admin' && role !== 'owner')) {
      return NextResponse.json(
        { error: 'Admin or owner permissions required to create credential sets' },
        { status: 403 }
      )
    }

    // Check org existence and name uniqueness in parallel
    const [orgExists, existingSet] = await Promise.all([
      db
        .select({ id: organization.id })
        .from(organization)
        .where(eq(organization.id, organizationId))
        .limit(1),
      db
        .select({ id: credentialSet.id })
        .from(credentialSet)
        .where(and(eq(credentialSet.organizationId, organizationId), eq(credentialSet.name, name)))
        .limit(1),
    ])

    if (orgExists.length === 0) {
      return NextResponse.json({ error: 'Organization not found' }, { status: 404 })
    }

    if (existingSet.length > 0) {
      return NextResponse.json(
        { error: 'A credential set with this name already exists' },
        { status: 409 }
      )
    }

    const now = new Date()
    const newCredentialSet = {
      id: generateId(),
      organizationId,
      name,
      description: description || null,
      providerId,
      createdBy: session.user.id,
      createdAt: now,
      updatedAt: now,
    }

    await db.insert(credentialSet).values(newCredentialSet)

    logger.info('Created credential set', {
      credentialSetId: newCredentialSet.id,
      organizationId,
      userId: session.user.id,
    })

    recordAudit({
      workspaceId: null,
      actorId: session.user.id,
      action: AuditAction.CREDENTIAL_SET_CREATED,
      resourceType: AuditResourceType.CREDENTIAL_SET,
      resourceId: newCredentialSet.id,
      actorName: session.user.name ?? undefined,
      actorEmail: session.user.email ?? undefined,
      resourceName: name,
      description: `Created credential set "${name}"`,
      metadata: { organizationId, providerId, credentialSetName: name },
      request: req,
    })

    return NextResponse.json(
      {
        credentialSet: {
          ...newCredentialSet,
          creatorName: session.user.name ?? null,
          creatorEmail: session.user.email ?? null,
          memberCount: 0,
        },
      },
      { status: 201 }
    )
  } catch (error) {
    logger.error('Error creating credential set', error)
    return NextResponse.json({ error: 'Failed to create credential set' }, { status: 500 })
  }
})
