// addRoutes combines the URL endpoints with the applications's services
// and dependencies and required middleware
func addRoutes(
	ctx context.Context,
	mux *http.ServeMux,
	database *sqlite.Database,
	static fs.FS,
	templ *template.Template,
) {
	mux.Handle("GET /", http.FileServer(http.FS(static)))
	mux.Handle("GET /board", api.Board(ctx, database, templ))
	mux.Handle("GET /edit-record/{id}", api.EditRecord(ctx, database, templ))
	mux.Handle("PATCH /patch-record/{id}", api.PatchRecord(ctx, database, templ))
	mux.Handle("DELETE /delete-record/{id}", api.DeleteRecord(ctx, database, templ))
}

const query = `SELECT u.id, u.name, u.username,  u.email, u.phone, u.website, a.street, a.suite, a.zipcode, a.city, c.name as company, c.catch_phrase, c.bs 
				FROM user u
				JOIN company c ON u.company_id = c.id
				JOIN address a ON u.address_id = a.id;
				`

// load user data and fill template
func Board(ctx context.Context, db *sqlite.Database, templ *template.Template) http.Handler {
	return http.HandlerFunc(

		func(w http.ResponseWriter, r *http.Request) {

			w.Header().Set("Content-Type", "text/html")

			records, err := sqlite.NoRowsOk(db.ReadRecords(ctx, query))
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			// Execute template with proper error handling
			if err := templ.ExecuteTemplate(w, "board", sqlite.Record{"records": records}); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		},
	)
}
