import { injectable } from 'inversify';
import { AdminApiClient } from '@/lib/api/admin/AdminApiClient';
import type { UserDto, DashboardStats, UserListResponse } from '@/lib/types/admin';
import { Result } from '@/lib/contracts/Result';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { DomainError, Service } from '@/lib/contracts/services/Service';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { getWebsiteServerEnv } from '@/lib/config/env';

/**
 * Admin Service - DTO Only
 *
 * Returns raw API DTOs. No ViewModels or UX logic.
 * All client-side presentation logic must be handled by presenters/templates.
 * @server-safe
 */
@injectable()
export class AdminService implements Service {
  private apiClient: AdminApiClient;

  constructor() {
    const baseUrl = getWebsiteApiBaseUrl();
    const logger = new ConsoleLogger();
    const { NODE_ENV } = getWebsiteServerEnv();
    const errorReporter = new EnhancedErrorReporter(logger, {
      showUserNotifications: false,
      logToConsole: true,
      reportToExternal: NODE_ENV === 'production',
    });
    this.apiClient = new AdminApiClient(baseUrl, errorReporter, logger);
  }

  /**
    * Get dashboard statistics
    */
   async getDashboardStats(): Promise<Result<DashboardStats, DomainError>> {
     // Mock data until API is implemented
     const mockStats: DashboardStats = {
       totalUsers: 1250,
       activeUsers: 1100,
       suspendedUsers: 50,
       deletedUsers: 100,
       systemAdmins: 5,
       recentLogins: 450,
       newUsersToday: 12,
       userGrowth: [
         { label: 'This week', value: 45, color: '#10b981' },
         { label: 'Last week', value: 38, color: '#3b82f6' },
       ],
       roleDistribution: [
         { label: 'Users', value: 1200, color: '#6b7280' },
         { label: 'Admins', value: 50, color: '#8b5cf6' },
       ],
       statusDistribution: {
         active: 1100,
         suspended: 50,
         deleted: 100,
       },
       activityTimeline: [
         { date: '2024-01-01', newUsers: 10, logins: 200 },
         { date: '2024-01-02', newUsers: 15, logins: 220 },
       ],
     };
     return Result.ok(mockStats);
   }

  /**
    * List users with filtering and pagination
    */
   async listUsers(): Promise<Result<UserListResponse, DomainError>> {
     // Mock data until API is implemented
     const mockUsers: UserDto[] = [
       {
         id: '1',
         email: 'admin@example.com',
         displayName: 'Admin User',
         roles: ['owner', 'admin'],
         status: 'active',
         isSystemAdmin: true,
         createdAt: '2024-01-01T00:00:00.000Z',
         updatedAt: '2024-01-01T00:00:00.000Z',
         lastLoginAt: '2024-01-15T10:00:00.000Z',
         primaryDriverId: 'driver-1',
       },
       {
         id: '2',
         email: 'user@example.com',
         displayName: 'Regular User',
         roles: ['user'],
         status: 'active',
         isSystemAdmin: false,
         createdAt: '2024-01-02T00:00:00.000Z',
         updatedAt: '2024-01-02T00:00:00.000Z',
         lastLoginAt: '2024-01-14T15:00:00.000Z',
       },
     ];

     const mockResponse: UserListResponse = {
       users: mockUsers,
       total: 2,
       page: 1,
       limit: 50,
       totalPages: 1,
     };

     return Result.ok(mockResponse);
   }

  /**
    * Update user status
    */
   async updateUserStatus(userId: string, status: string): Promise<Result<UserDto, DomainError>> {
     // Mock success until API is implemented
     return Result.ok({
       id: userId,
       email: 'mock@example.com',
       displayName: 'Mock User',
       roles: ['user'],
       status,
       isSystemAdmin: false,
       createdAt: '2024-01-01T00:00:00.000Z',
       updatedAt: '2024-01-01T00:00:00.000Z',
     });
   }

  /**
    * Delete a user (soft delete)
    */
   async deleteUser(): Promise<Result<void, DomainError>> {
     // Mock success until API is implemented
     return Result.ok(undefined);
   }
}