package home

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"log"
	"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"
	"source.toby3d.me/toby3d/home/internal/middleware"
	"source.toby3d.me/toby3d/home/internal/page"
	pagefsrepo "source.toby3d.me/toby3d/home/internal/page/repository/fs"
	pageucase "source.toby3d.me/toby3d/home/internal/page/usecase"
	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"
)

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)
	pages := pagefsrepo.NewFileSystemPageRepository(contentDir)
	pager := pageucase.NewPageUseCase(pages, resources)
	server := servercase.NewServerUseCase()
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// INFO(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 secured by middleware or
		// something else.
		if static, err := staticer.Do(r.Context(), strings.TrimPrefix(r.URL.Path, "/")); err == nil {
			http.ServeContent(w, r, static.Name(), static.ModTime(), static)

			return
		}

		lang := domain.LanguageUnd

		s, err := siter.Do(r.Context(), lang)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)

			return
		}

		siteServer, err := server.Do(r.Context(), *s)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)

			return
		}

		for i := range siteServer.Headers {
			if !siteServer.Headers[i].IsMatched(r.URL.Path) {
				continue
			}

			for name, value := range siteServer.Headers[i].Values {
				w.Header().Add(name, value)
			}
		}

		var redirect *domain.Redirect
		for i := range siteServer.Redirects {
			if !siteServer.Redirects[i].IsMatch(r.URL.Path) {
				continue
			}

			if siteServer.Redirects[i].Force {
				http.Redirect(w, r, siteServer.Redirects[i].To, siteServer.Redirects[i].Status)

				return
			}

			redirect = &siteServer.Redirects[i]

			break
		}

		if s.IsMultiLingual() {
			head, tail := urlutil.ShiftPath(r.URL.Path)

			if head == "" {
				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, _, err := language.ParseAcceptLanguage(
					r.Header.Get(common.HeaderAcceptLanguage))
				if err != nil || len(requested) == 0 {
					requested = append(requested, language.English)
				}

				matched, _, _ := language.NewMatcher(supported).Match(requested...)
				lang = domain.NewLanguage(matched.String())

				http.Redirect(w, r, "/"+lang.Lang()+"/", http.StatusSeeOther)

				return
			}

			lang = domain.NewLanguage(head)
			r.URL.Path = tail
		}

		if lang == domain.LanguageUnd && redirect != nil {
			http.Redirect(w, r, redirect.To, redirect.Status)

			return
		}

		if s, err = siter.Do(r.Context(), lang); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)

			return
		}

		if siteServer, err = server.Do(r.Context(), *s); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)

			return
		}

		for i := range siteServer.Headers {
			if !siteServer.Headers[i].IsMatched(r.URL.Path) {
				continue
			}

			for name, value := range siteServer.Headers[i].Values {
				w.Header().Add(name, value)
			}
		}

		for i := range siteServer.Redirects {
			if !siteServer.Redirects[i].IsMatch(r.URL.Path) {
				continue
			}

			if siteServer.Redirects[i].Force {
				http.Redirect(w, r, siteServer.Redirects[i].To, siteServer.Redirects[i].Status)

				return
			}

			redirect = &siteServer.Redirects[i]

			break
		}

		p, err := pager.Do(r.Context(), lang, r.URL.Path)
		if err != nil {
			if !errors.Is(err, page.ErrNotExist) {
				http.Error(w, err.Error(), http.StatusInternalServerError)

				return
			}

			if redirect != nil {
				http.Redirect(w, r, redirect.To, redirect.Status)

				return
			}

			res, err := resourcer.Do(r.Context(), r.URL.Path)
			if err != nil {
				if errors.Is(err, fs.ErrNotExist) {
					http.Error(w, err.Error(), http.StatusNotFound)

					return
				}

				http.Error(w, err.Error(), http.StatusInternalServerError)

				return
			}

			// TODO(toby3d) : ugly workaround, must be refactored
			resFile, err := contentDir.Open(res.File.Path())
			if err != nil {
				http.Error(w, "cannot open: "+err.Error(), http.StatusInternalServerError)

				return
			}
			defer resFile.Close()

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

				return
			}
			defer resFile.Close()

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

			return
		}

		contentLanguage := make([]string, len(p.Translations))
		for i := range p.Translations {
			contentLanguage[i] = p.Translations[i].Language.Code()
		}

		w.Header().Set(common.HeaderContentLanguage, strings.Join(contentLanguage, ", "))

		template, err := themer.Do(r.Context(), s, p)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)

			return
		}

		w.Header().Set(common.HeaderContentType, common.MIMETextHTMLCharsetUTF8)
		if err = template(w); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
	chain := middleware.Chain{middleware.LogFmt()}

	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 {
	var err error
	if ln != nil {
		err = a.server.Serve(ln)
	} else {
		err = a.server.ListenAndServe()
	}

	if 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
}
