import { Injectable, signal, computed } from '@angular/core';
import { Router } from '@angular/router';
import { inject } from '@angular/core';

export interface AuthUser {
  email: string;
  name: string;
  role: string;
  avatar?: string;
}

interface DummyUser {
  email: string;
  password: string;
  name: string;
  role: string;
}

const COOKIE_NAME = 'crm_auth_session';
const COOKIE_MAX_AGE_DAYS = 7;

const DUMMY_USERS: DummyUser[] = [
  {
    email: 'admin@crm.com',
    password: 'admin123',
    name: 'John Doe',
    role: 'admin',
  },
];

@Injectable({ providedIn: 'root' })
export class AuthService {
  private readonly router = inject(Router);

  private readonly _currentUser = signal<AuthUser | null>(this.loadFromCookie());
  private readonly _isLoading = signal(false);

  readonly currentUser = this._currentUser.asReadonly();
  readonly isAuthenticated = computed(() => !!this._currentUser());
  readonly isLoading = this._isLoading.asReadonly();

  login(email: string, password: string): { success: boolean; error?: string } {
    this._isLoading.set(true);

    const matched = DUMMY_USERS.find(
      (u) => u.email === email && u.password === password,
    );

    if (!matched) {
      this._isLoading.set(false);
      return { success: false, error: 'Invalid email or password' };
    }

    const user: AuthUser = {
      email: matched.email,
      name: matched.name,
      role: matched.role,
    };

    this._currentUser.set(user);
    this.saveToCookie(user);
    this._isLoading.set(false);

    return { success: true };
  }

  logout(): void {
    this._currentUser.set(null);
    this.removeCookie();
    this.router.navigate(['/auth/signin']);
  }

  getCurrentUser(): AuthUser | null {
    return this._currentUser();
  }

  // ---------------------------------------------------------------------------
  // Cookie helpers
  // ---------------------------------------------------------------------------

  private loadFromCookie(): AuthUser | null {
    try {
      const value = this.getCookie(COOKIE_NAME);
      if (!value) return null;
      return JSON.parse(decodeURIComponent(value)) as AuthUser;
    } catch {
      return null;
    }
  }

  private saveToCookie(user: AuthUser): void {
    try {
      const encoded = encodeURIComponent(JSON.stringify(user));
      const expires = new Date();
      expires.setDate(expires.getDate() + COOKIE_MAX_AGE_DAYS);
      document.cookie = `${COOKIE_NAME}=${encoded}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
    } catch {
      // cookie unavailable – silently ignore
    }
  }

  private removeCookie(): void {
    try {
      document.cookie = `${COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax`;
    } catch {
      // silently ignore
    }
  }

  private getCookie(name: string): string | null {
    const match = document.cookie.match(
      new RegExp('(?:^|;\\s*)' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*=\\s*([^;]*)'),
    );
    return match ? match[1] : null;
  }
}
