import { prisma } from '../../config/database';
import { rocketchatClient } from '../../services/rocketchat.client';
import { rocketchatProvisioner } from '../../services/user-provisioning/rocketchat.provisioner';
import { logger } from '../../utils/logger';
import type { CMUser } from '../../services/user-provisioning/provisioner.interface';

class RocketChatService {
  /**
   * Get a Rocket.Chat auth token for the given Changemaker user.
   * Provisions / syncs the RC user as needed (delegates to provisioner).
   */
  async getAuthToken(changemakerUserId: string): Promise<{
    authToken: string;
    rcUserId: string;
  }> {
    const user = await prisma.user.findUnique({ where: { id: changemakerUserId } });
    if (!user) throw new Error('User not found');

    const cmUser: CMUser = {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role,
      roles: user.roles,
      status: user.status,
      permissions: user.permissions as Record<string, unknown> | null,
    };

    // Check for cached RC user ID
    const permissions = (user.permissions as Record<string, unknown>) || {};
    let rcUserId = permissions._rcUserId as string | undefined;

    if (!rcUserId) {
      // Provision via the provisioner framework
      const result = await rocketchatProvisioner.provision(cmUser);
      if (!result.success || !result.serviceUserId) {
        throw new Error(result.error || 'Failed to provision RC user');
      }
      rcUserId = result.serviceUserId;
    }

    // Get auth token (also syncs roles)
    const authToken = await rocketchatProvisioner.getAuthToken(cmUser, rcUserId);
    if (!authToken) throw new Error('Failed to get RC auth token');

    return { authToken, rcUserId };
  }

  /** Setup default channels on first use */
  async ensureDefaultChannels(): Promise<void> {
    try {
      await rocketchatClient.ensureChannel('shifts', 'Shift coordination and updates');
      await rocketchatClient.ensureChannel('canvassing', 'Canvass activity and updates');
      await rocketchatClient.ensureChannel('campaigns', 'Campaign activity and responses');
      logger.info('RC default channels verified');
    } catch (err) {
      logger.warn('RC ensureDefaultChannels failed:', err);
    }
  }
}

export const rocketchatService = new RocketChatService();
