# frozen_string_literal: true

class Api::SyncController < Api::ApiController
  def index
    accessible_projects = current_user.accessible_projects_for(Current.account)
    @accounts = filter(current_user.accounts)
    @projects = filter(Project).all
    @contract_templates = filter(ContractTemplate.where(project: accessible_projects)).all
    @acquired_media_releases = (AcquiredMediaRelease.where(project: accessible_projects))
    @appearance_releases = (AppearanceRelease.where(project: accessible_projects))
    @location_releases = (LocationRelease.where(project: accessible_projects))
    @material_releases = (MaterialRelease.where(project: accessible_projects))
    @talent_releases = (TalentRelease.where(project: accessible_projects))
    @notes = notes_query(Note.where(notable: @appearance_releases + @location_releases + @material_releases + @talent_releases + @acquired_media_releases ))

    render json: {
      data: {
        accounts: @accounts,
        projects: @projects,
        contract_templates: @contract_templates,
        acquired_media_releases: releases_query(@acquired_media_releases),
        appearance_releases: releases_query(@appearance_releases),
        location_releases: releases_query(@location_releases),
        material_releases: releases_query(@material_releases),
        talent_releases: releases_query(@talent_releases),
        notes: @notes
      }
    }
  end

  private

  def releases_query(release)
    filter(release).all.map { |release| release_json(release) }
  end

  def notes_query(notes)
    filter(notes).all.map do |note|
      json = note.as_json 
      json[:attributes][:email] = note.email
      json
    end
  end

  def release_json(release)
    json = release.as_json

    unless release.model_name.to_s == "AcquiredMediaRelease"
      json[:attributes][:photos] = release.photos.map do |photo|
        build_photo_object photo
      end
    end

    if release.respond_to?(:guardian_photo)
      photo = release.guardian_photo
      json[:attributes][:guardian_photo] = photo.attached? ? build_photo_object(photo) : nil
    end

    json
  end

  def filter(relation)
    policy_scope(relation)
  end

  def build_photo_object(photo)
    {
      id: photo.id.to_s,
      type: 'active_storage_attachment',
      attributes: {
          filename: photo.filename.to_s,
          content_type: photo.content_type,
          url: Rails.application.routes.url_helpers.rails_blob_url(photo, host: AppHost.new.domain_with_port),
          thumbnail_url: Rails.application.routes.url_helpers.rails_representation_url(photo.variant(resize: '150x150'), host: AppHost.new.domain_with_port)
      }
    }
  end
 end
