import { Result } from '@/lib/contracts/Result';
import { HomeService } from '@/lib/services/home/HomeService';
import type { HomeViewData } from '@/templates/HomeTemplate';
import type { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { HomeViewDataBuilder } from '@/lib/builders/view-data/HomeViewDataBuilder';

/**
 * HomePageQuery
 *
 * Server-side data fetcher for the home page.
 * Returns Result<HomeViewData, string>
 */
export class HomePageQuery implements PageQuery<HomeViewData, void, string> {
  /**
   * Execute the home page query
   *
   * @returns Result with HomeViewData or error
   */
  async execute(): Promise<Result<HomeViewData, string>> {
    try {
      const service = new HomeService();
      const result = await service.getHomeData();

      if (result.isErr()) {
        return Result.err('Error');
      }

      const viewData = HomeViewDataBuilder.build(result.unwrap());
      return Result.ok(viewData);
    } catch (error) {
      console.error('HomePageQuery failed:', error);
      return Result.err('Error');
    }
  }

  /**
   * Static execute for convenience
   */
  static async execute(): Promise<Result<HomeViewData, string>> {
    return new HomePageQuery().execute();
  }

  /**
   * Check if user should be redirected to dashboard
   */
  static async shouldRedirectToDashboard(): Promise<boolean> {
    const service = new HomeService();
    return service.shouldRedirectToDashboard();
  }
}
