package home

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/fs"
	"log"
	"mime"
	"net"
	"net/http"
	"os"
	"strings"
	"time"

	"golang.org/x/text/language"

	"source.toby3d.me/toby3d/home/internal/common"
	"source.toby3d.me/toby3d/home/internal/domain"
	entryhttpdelivery "source.toby3d.me/toby3d/home/internal/entry/delivery/http"
	pagefsrepo "source.toby3d.me/toby3d/home/internal/entry/repository/fs"
	pageucase "source.toby3d.me/toby3d/home/internal/entry/usecase"
	"source.toby3d.me/toby3d/home/internal/middleware"
	resourcefsrepo "source.toby3d.me/toby3d/home/internal/resource/repository/fs"
	resourceucase "source.toby3d.me/toby3d/home/internal/resource/usecase"
	servercase "source.toby3d.me/toby3d/home/internal/server/usecase"
	sitefsrepo "source.toby3d.me/toby3d/home/internal/site/repository/fs"
	siteucase "source.toby3d.me/toby3d/home/internal/site/usecase"
	staticfsrepo "source.toby3d.me/toby3d/home/internal/static/repository/fs"
	staticucase "source.toby3d.me/toby3d/home/internal/static/usecase"
	themefsrepo "source.toby3d.me/toby3d/home/internal/theme/repository/fs"
	themeucase "source.toby3d.me/toby3d/home/internal/theme/usecase"
	"source.toby3d.me/toby3d/home/internal/urlutil"
	webfingerhttpdelivery "source.toby3d.me/toby3d/home/internal/webfinger/delivery/http"
	webfingerucase "source.toby3d.me/toby3d/home/internal/webfinger/usecase"
)

type App struct {
	server *http.Server
}

func NewApp(logger *log.Logger, config *domain.Config) (*App, error) {
	themeDir := os.DirFS(config.ThemeDir)
	partialsDir, err := fs.Sub(themeDir, "partials")
	if err != nil {
		return nil, fmt.Errorf("cannot substitute into partials subdirectory: %w", err)
	}

	contentDir := os.DirFS(config.ContentDir)
	resources := resourcefsrepo.NewFileServerResourceRepository(contentDir)
	sites := sitefsrepo.NewFileSystemSiteRepository(contentDir)
	siter := siteucase.NewSiteUseCase(sites, resources)
	staticDir := os.DirFS(config.StaticDir)
	statics := staticfsrepo.NewFileServerStaticRepository(staticDir)
	staticer := staticucase.NewStaticUseCase(statics)
	resourcer := resourceucase.NewResourceUseCase(resources)
	themes := themefsrepo.NewFileSystemThemeRepository(themeDir)
	themer := themeucase.NewThemeUseCase(partialsDir, themes)
	entries := pagefsrepo.NewFileSystemPageRepository(contentDir)
	entrier := pageucase.NewEntryUseCase(entries, resources)
	serverer := servercase.NewServerUseCase(sites)
	webfingerer := webfingerucase.NewWebFingerUseCase(sites)
	webfingerHandler := webfingerhttpdelivery.NewHandler(webfingerer)
	entryHandler := entryhttpdelivery.NewHandler(siter, entrier, themer)
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// NOTE(toby3d): any static file is public and unprotected by
		// design, so it's safe to search it first before deep down to
		// any page or it's resource which might be protected by
		// middleware or something else.
		if static, err := staticer.Do(r.Context(), r.URL.Path); err == nil {
			http.ServeContent(w, r, static.Name(), static.ModTime(), static)

			return
		}

		head, tail := urlutil.ShiftPath(r.URL.Path)

		switch strings.ToLower(head) {
		case "":
			contentType, _, _ := mime.ParseMediaType(r.Header.Get(common.HeaderAccept))

			switch contentType {
			case common.MIMEApplicationLdJSON: // NOTE(toby3d): show entry as ActivityPub object.
				entryHandler.ServeHTTP(w, r)

				return
			}

			// NOTE(toby3d): read $HOME_CONTENT_DIR/index.md as a source of
			// truth and global settings for any child entry.
			s, err := siter.Do(r.Context(), domain.LanguageUnd)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)

				return
			}

			if s.IsMultiLingual() {
				supported := make([]language.Tag, len(s.Languages))
				for i := range s.Languages {
					supported[i] = language.Make(s.Languages[i].Lang())
				}

				if s.DefaultLanguage != domain.LanguageUnd {
					supported = append([]language.Tag{language.Make(s.DefaultLanguage.Code())},
						supported...)
				}

				requested, _, _ := language.ParseAcceptLanguage(r.Header.Get(
					common.HeaderAcceptLanguage))
				if len(requested) == 0 {
					requested = append(requested, language.English)
				}

				matched, _, _ := language.NewMatcher(supported).Match(requested...)
				http.Redirect(w, r, "/"+domain.NewLanguage(matched.String()).Lang()+"/",
					http.StatusSeeOther)

				return
			}
		case ".well-known":
			switch strings.ToLower(tail) {
			case "/webfinger":
				webfingerHandler.ServeHTTP(w, r)

				return
			}
		}

		if res, err := resourcer.Do(r.Context(), tail); err == nil {
			// TODO(toby3d) : ugly workaround, must be refactored
			resFile, err := contentDir.Open(res.File.Filename())
			if err != nil {
				http.Error(w, "cannot open resource: "+err.Error(), http.StatusInternalServerError)

				return
			}
			defer resFile.Close()

			resBytes, err := io.ReadAll(resFile)
			if err != nil {
				http.Error(w, "cannot read resource: "+err.Error(), http.StatusInternalServerError)

				return
			}
			defer resFile.Close()

			http.ServeContent(w, r, res.Name(), domain.ResourceModTime(res), bytes.NewReader(resBytes))

			return
		}

		entryHandler.ServeHTTP(w, r)
	})
	chain := middleware.Chain{
		// middleware.LogFmt(),
		middleware.Redirect(middleware.RedirectConfig{Serverer: serverer}),
		middleware.Header(middleware.HeaderConfig{Serverer: serverer}),
	}

	return &App{server: &http.Server{
		Addr:         config.AddrPort().String(),
		Handler:      chain.Handler(handler),
		ErrorLog:     logger,
		WriteTimeout: 500 * time.Millisecond,
	}}, nil
}

func (a *App) Run(ln net.Listener) error {
	if err := a.server.Serve(ln); err != nil {
		return fmt.Errorf("cannot listen and serve server: %w", err)
	}

	return nil
}

func (a *App) Stop(ctx context.Context) error {
	if err := a.server.Shutdown(ctx); err != nil {
		return fmt.Errorf("failed to shutdown app: %w", err)
	}

	return nil
}
