import { Injectable, NotFoundException } from '@nestjs/common';
import { TenantService } from '../tenant/tenant.service';
import { UserService } from '../user/user.service';
import { User } from '../user/user.entity';
import { UserRole } from '../user/user-role.enum';

@Injectable()
export class SuperAdminService {
    constructor(
        private readonly tenantService: TenantService,
        private readonly userService: UserService,
    ) { }

    async getAllTenants(page?: number, limit?: number) {
        return this.tenantService.findAll(page, limit);
    }

    async createTenant(name: string, domain?: string, adminUserId?: string, parentId?: string) {
        const tenant = await this.tenantService.create(name, domain, parentId);
        if (adminUserId) {
            await this.tenantService.addMember(tenant.id, adminUserId, UserRole.TENANT_ADMIN);
        }
        return tenant;
    }

    async assignUserToTenant(userId: string, tenantId: string, role: UserRole = UserRole.TENANT_ADMIN) {
        // Find existing members of this tenant
        const members = await this.tenantService.getMembers(tenantId);

        // Remove existing admins from this tenant (unlinking them, not changing their role)
        for (const member of members.data) {
            if (member.role === UserRole.TENANT_ADMIN || member.role === UserRole.SUPER_ADMIN) {
                await this.tenantService.removeMember(tenantId, member.userId);
            }
        }

        // Add the new admin association for this tenant
        return this.tenantService.addMember(tenantId, userId, role);
    }

    async createTenantAdmin(tenantId: string, username: string, password?: string) {
        const defaultPassword = password || Math.random().toString(36).slice(-8);
        const result = await this.userService.createUser(
            username,
            defaultPassword,
            false, // isAdmin
            tenantId,
            username // displayName
        );
        return {
            user: result.user,
            defaultPassword: defaultPassword
        };
    }

    async updateTenant(tenantId: string, data: { name?: string; domain?: string; parentId?: string }) {
        return this.tenantService.update(tenantId, data);
    }

    async deleteTenant(tenantId: string) {
        return this.tenantService.remove(tenantId);
    }

    // NOTE: Model Management would be added here depending on ModelService functionality
}
