import { Response, NextFunction } from 'express'
import { AuthRequest } from './auth.js'
import { tenantContextStorage, getTenantPool } from '../config/tenant-db.js'
import { sendError } from './error.js'
import adminPool from '../config/admin-pool.js'

export async function tenantDbMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
  if (!req.user || !req.user.tenantId) {
    return next()
  }

  try {
    const result = await adminPool.query(
      'SELECT tenant_id, db_host, db_port, db_name, db_user, db_password, status FROM tenant_configs WHERE tenant_id = $1',
      [req.user.tenantId]
    )

    if (result.rows.length === 0) {
      return sendError(res, 'Tenant not found', 404)
    }

    const config = result.rows[0]
    if (config.status !== 'active') {
      return sendError(res, 'Tenant is inactive', 403)
    }

    const tenantPool = getTenantPool({
      tenantId: config.tenant_id,
      dbHost: config.db_host,
      dbPort: config.db_port,
      dbName: config.db_name,
      dbUser: config.db_user,
      dbPassword: config.db_password,
    })

    tenantContextStorage.run({ tenantId: config.tenant_id, pool: tenantPool, scope: req.user ? {
      role: req.user.role,
      storeCode: req.user.storeCode,
      region: req.user.region,
    } : null }, () => {
      next()
    })
  } catch (err: any) {
    return sendError(res, `Tenant DB error: ${err.message}`)
  }
}
