// src/client/shared/api/repositories/AuthRepository.ts
// Auth Repository for login/logout operations with Zod validation

import { z } from 'zod';
import { BaseRepository, type RepositoryConfig } from '../BaseRepository';
import type { RequestConfig } from '../api.client';

/**
 * Схемы для валидации запросов/ответов (синхронизированы с бэкендом)
 */

// User Response (без пароля!)
export const userResponseSchema = z.object({
  id: z.string(),
  username: z.string(),
  fullName: z.string().nullable(),
  email: z.string().nullable(),
  role: z.string(),
  position: z.string().nullable(),
  employeeId: z.string(),
});

export type UserResponse = z.infer<typeof userResponseSchema>;

// Login Request
export const loginRequestSchema = z.object({
  username: z.string().min(1, 'Username is required'),
  password: z.string().min(1, 'Password is required'),
});

export type LoginRequest = z.infer<typeof loginRequestSchema>;

// Login Response
export const loginResponseSchema = z.object({
  user: userResponseSchema,
});

export type LoginResponse = z.infer<typeof loginResponseSchema>;

// Logout Response
export const logoutResponseSchema = z.object({
  success: z.boolean(),
});

export type LogoutResponse = z.infer<typeof logoutResponseSchema>;

/**
 * Auth Repository
 */
export class AuthRepository extends BaseRepository {
  protected basePath = '/auth';

  /**
   * Выполняет вход в систему
   */
  async login(credentials: LoginRequest): Promise<LoginResponse> {
    const config: RequestConfig<LoginResponse> = {
      schema: loginResponseSchema,
    };

    return this.post<LoginRequest, LoginResponse>('/login', credentials, config);
  }

  /**
   * Выполняет гостевой вход через системный VIEWER-аккаунт
   */
  async guestLogin(): Promise<LoginResponse> {
    const config: RequestConfig<LoginResponse> = {
      schema: loginResponseSchema,
    };

    return this.post<{}, LoginResponse>('/guest', {}, config);
  }

  /**
   * Выполняет выход из системы
   */
  async logout(): Promise<LogoutResponse> {
    const config: RequestConfig<LogoutResponse> = {
      schema: logoutResponseSchema,
    };

    return this.post<{}, LogoutResponse>('/logout', {}, config);
  }

  /**
   * Получает текущего пользователя (если сессия активна)
   */
  async getCurrentUser(): Promise<UserResponse> {
    const config: RequestConfig<UserResponse> = {
      schema: userResponseSchema,
    };

    return this.get<UserResponse>('/me', config);
  }
}

/**
 * Синглтон экземпляр AuthRepository
 */
export const authRepository = new AuthRepository();
