import db from '../../config/database';
import { v4 as uuidv4 } from 'uuid';

export interface User {
  id: string;
  username: string;
  email: string;
  passwordHash: string;
  role: string;
  tenantId: string;
  createdAt: Date;
  updatedAt: Date;
}

export class UserService {
  static async createUser(userData: Partial<User> & { password: string }): Promise<{ success: boolean; userId?: string; error?: string }> {
    try {
      const userId = uuidv4();
      await db('cf_users').insert({
        id: userId,
        username: userData.username,
        email: userData.email,
        password_hash: userData.password,
        role: userData.role || 'OPERATOR',
        tenant_id: userData.tenantId,
        created_at: new Date(),
        updated_at: new Date()
      });
      return { success: true, userId };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  static async getUserById(userId: string): Promise<User | null> {
    const user = await db('cf_users').where({ id: userId }).first();
    return user || null;
  }

  static async updateUser(userId: string, updateData: Partial<User>): Promise<{ success: boolean }> {
    await db('cf_users').where({ id: userId }).update({
      ...updateData,
      updated_at: new Date()
    });
    return { success: true };
  }

  static async listUsers(tenantId: string): Promise<User[]> {
    return await db('cf_users').where({ tenant_id: tenantId });
  }

  static async deleteUser(userId: string): Promise<void> {
    await db('cf_users').where({ id: userId }).del();
  }
}

export default UserService;
