package store

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/ponzischeme89/memby/server/internal/appupdate"
)

// MaintenanceKey is the app_settings row backing maintenance mode.
const MaintenanceKey = "maintenance"

// RequestPolicyKey controls which Emby users may send titles to Sonarr/Radarr.
const RequestPolicyKey = "request_policy"

// PlaybackPolicyKey controls presentation behavior that should be adjustable without
// shipping a new TV build.
const PlaybackPolicyKey = "playback_policy"

// MDBListSettingsKey stores the optional movie-ratings integration. The API key stays
// in this server-owned document and is never included in client or admin status payloads.
const MDBListSettingsKey = "mdblist_settings"

var defaultMDBListSources = []string{
	"imdb", "tomatoes", "audience", "metacritic", "letterboxd", "rogerebert",
	"tmdb", "trakt", "mal", "anilist", "anidb", "kitsu", "score", "score_average",
}

type MDBListSettings struct {
	Enabled   bool      `json:"enabled"`
	APIKey    string    `json:"apiKey"`
	Sources   []string  `json:"sources"`
	UpdatedAt time.Time `json:"updatedAt"`
}

func DefaultMDBListSettings() MDBListSettings {
	return MDBListSettings{Sources: append([]string(nil), defaultMDBListSources...)}
}

func MDBListSources() []string {
	return append([]string(nil), defaultMDBListSources...)
}

func ValidMDBListSource(source string) bool {
	source = strings.ToLower(strings.TrimSpace(source))
	for _, supported := range defaultMDBListSources {
		if source == supported {
			return true
		}
	}
	return false
}

func normalizeMDBListSettings(settings MDBListSettings) MDBListSettings {
	settings.APIKey = strings.TrimSpace(settings.APIKey)
	seen := map[string]bool{}
	sources := make([]string, 0, len(settings.Sources))
	for _, source := range settings.Sources {
		source = strings.ToLower(strings.TrimSpace(source))
		if !ValidMDBListSource(source) || seen[source] {
			continue
		}
		seen[source] = true
		sources = append(sources, source)
	}
	if len(sources) == 0 {
		sources = append(sources, defaultMDBListSources...)
	}
	settings.Sources = sources
	return settings
}

func (s *Store) MDBListSettings(ctx context.Context) (MDBListSettings, error) {
	var raw []byte
	err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, MDBListSettingsKey).Scan(&raw)
	if errors.Is(err, pgx.ErrNoRows) {
		return DefaultMDBListSettings(), nil
	}
	if err != nil {
		return DefaultMDBListSettings(), fmt.Errorf("store: read MDBList settings: %w", err)
	}
	var settings MDBListSettings
	if err := json.Unmarshal(raw, &settings); err != nil {
		return DefaultMDBListSettings(), fmt.Errorf("store: decode MDBList settings: %w", err)
	}
	return normalizeMDBListSettings(settings), nil
}

func (s *Store) SetMDBListSettings(ctx context.Context, settings MDBListSettings) error {
	settings = normalizeMDBListSettings(settings)
	settings.UpdatedAt = time.Now().UTC()
	raw, err := json.Marshal(settings)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, `
		INSERT INTO app_settings (key, value, updated_at)
		VALUES ($1, $2::jsonb, now())
		ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
		MDBListSettingsKey, string(raw))
	if err != nil {
		return fmt.Errorf("store: write MDBList settings: %w", err)
	}
	return nil
}

// FeaturePolicyKey is the durable operator control plane for optional behaviour.
// The catalogue of valid flags lives in the API; the store only persists overrides so
// removing or renaming a feature does not strand an unreadable database row.
const FeaturePolicyKey = "feature_policy"

type FeaturePolicySnapshot struct {
	Overrides map[string]bool `json:"overrides"`
	SafeMode  bool            `json:"safeMode"`
	Revision  int64           `json:"revision"`
	UpdatedAt time.Time       `json:"updatedAt"`
}

type FeaturePolicy struct {
	Overrides map[string]bool        `json:"overrides"`
	SafeMode  bool                   `json:"safeMode"`
	Revision  int64                  `json:"revision"`
	UpdatedAt time.Time              `json:"updatedAt"`
	Previous  *FeaturePolicySnapshot `json:"previous,omitempty"`
}

var ErrFeaturePolicyConflict = errors.New("store: feature policy revision conflict")

func DefaultFeaturePolicy() FeaturePolicy {
	return FeaturePolicy{Overrides: map[string]bool{}}
}

func normalizeFeaturePolicy(policy FeaturePolicy) FeaturePolicy {
	if policy.Overrides == nil {
		policy.Overrides = map[string]bool{}
	}
	return policy
}

func (s *Store) FeaturePolicy(ctx context.Context) (FeaturePolicy, error) {
	var raw []byte
	err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, FeaturePolicyKey).Scan(&raw)
	if errors.Is(err, pgx.ErrNoRows) {
		return DefaultFeaturePolicy(), nil
	}
	if err != nil {
		return DefaultFeaturePolicy(), fmt.Errorf("store: read feature policy: %w", err)
	}
	var policy FeaturePolicy
	if err := json.Unmarshal(raw, &policy); err != nil {
		return DefaultFeaturePolicy(), fmt.Errorf("store: decode feature policy: %w", err)
	}
	return normalizeFeaturePolicy(policy), nil
}

// SetFeaturePolicy preserves the prior revision inside the same durable document. This
// gives the operator a recovery button without requiring a matching client release.
func (s *Store) SetFeaturePolicy(
	ctx context.Context, next FeaturePolicy, expectedRevision int64,
) (FeaturePolicy, error) {
	tx, err := s.pool.Begin(ctx)
	if err != nil {
		return FeaturePolicy{}, fmt.Errorf("store: begin feature policy write: %w", err)
	}
	defer func() { _ = tx.Rollback(ctx) }()
	if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, FeaturePolicyKey); err != nil {
		return FeaturePolicy{}, fmt.Errorf("store: lock feature policy: %w", err)
	}
	current := DefaultFeaturePolicy()
	var currentRaw []byte
	err = tx.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, FeaturePolicyKey).Scan(&currentRaw)
	if err == nil {
		if err := json.Unmarshal(currentRaw, &current); err != nil {
			return FeaturePolicy{}, fmt.Errorf("store: decode current feature policy: %w", err)
		}
		current = normalizeFeaturePolicy(current)
	} else if !errors.Is(err, pgx.ErrNoRows) {
		return FeaturePolicy{}, fmt.Errorf("store: read current feature policy: %w", err)
	}
	if current.Revision != expectedRevision {
		return FeaturePolicy{}, ErrFeaturePolicyConflict
	}
	next = normalizeFeaturePolicy(next)
	next.Revision = current.Revision + 1
	next.UpdatedAt = time.Now().UTC()
	next.Previous = &FeaturePolicySnapshot{
		Overrides: current.Overrides, SafeMode: current.SafeMode,
		Revision: current.Revision, UpdatedAt: current.UpdatedAt,
	}
	raw, err := json.Marshal(next)
	if err != nil {
		return FeaturePolicy{}, err
	}
	_, err = tx.Exec(ctx, `
		INSERT INTO app_settings (key, value, updated_at)
		VALUES ($1, $2::jsonb, now())
		ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
		FeaturePolicyKey, string(raw))
	if err != nil {
		return FeaturePolicy{}, fmt.Errorf("store: write feature policy: %w", err)
	}
	if err := tx.Commit(ctx); err != nil {
		return FeaturePolicy{}, fmt.Errorf("store: commit feature policy: %w", err)
	}
	return next, nil
}

const DefaultPrerollDurationMs int64 = 6_500

type PlaybackPolicy struct {
	PrerollEnabled    bool      `json:"prerollEnabled"`
	PrerollDurationMs int64     `json:"prerollDurationMs"`
	UpdatedAt         time.Time `json:"updatedAt"`
}

func DefaultPlaybackPolicy() PlaybackPolicy {
	return PlaybackPolicy{PrerollEnabled: true, PrerollDurationMs: DefaultPrerollDurationMs}
}

func normalizePlaybackPolicy(policy PlaybackPolicy) PlaybackPolicy {
	if policy.PrerollDurationMs == 0 {
		policy.PrerollDurationMs = DefaultPrerollDurationMs
	}
	policy.PrerollDurationMs = max(int64(1_000), min(policy.PrerollDurationMs, int64(30_000)))
	return policy
}

func (s *Store) PlaybackPolicy(ctx context.Context) (PlaybackPolicy, error) {
	var raw []byte
	err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, PlaybackPolicyKey).Scan(&raw)
	if errors.Is(err, pgx.ErrNoRows) {
		return DefaultPlaybackPolicy(), nil
	}
	if err != nil {
		return DefaultPlaybackPolicy(), fmt.Errorf("store: read playback policy: %w", err)
	}
	var policy PlaybackPolicy
	if err := json.Unmarshal(raw, &policy); err != nil {
		return DefaultPlaybackPolicy(), fmt.Errorf("store: decode playback policy: %w", err)
	}
	return normalizePlaybackPolicy(policy), nil
}

func (s *Store) SetPlaybackPolicy(ctx context.Context, policy PlaybackPolicy) error {
	policy = normalizePlaybackPolicy(policy)
	policy.UpdatedAt = time.Now().UTC()
	raw, err := json.Marshal(policy)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, `
		INSERT INTO app_settings (key, value, updated_at)
		VALUES ($1, $2::jsonb, now())
		ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
		PlaybackPolicyKey, string(raw))
	if err != nil {
		return fmt.Errorf("store: write playback policy: %w", err)
	}
	return nil
}

type RequestPolicy struct {
	AllowedUserIDs []string  `json:"allowedUserIds"`
	UpdatedAt      time.Time `json:"updatedAt"`
}

func (p RequestPolicy) Allows(userID string) bool {
	for _, allowed := range p.AllowedUserIDs {
		if allowed == userID {
			return true
		}
	}
	return false
}

func (s *Store) RequestPolicy(ctx context.Context) (RequestPolicy, error) {
	var raw []byte
	err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, RequestPolicyKey).Scan(&raw)
	if errors.Is(err, pgx.ErrNoRows) {
		return RequestPolicy{AllowedUserIDs: []string{}}, nil
	}
	if err != nil {
		return RequestPolicy{}, fmt.Errorf("store: read request policy: %w", err)
	}
	var policy RequestPolicy
	if err := json.Unmarshal(raw, &policy); err != nil {
		return RequestPolicy{}, fmt.Errorf("store: decode request policy: %w", err)
	}
	if policy.AllowedUserIDs == nil {
		policy.AllowedUserIDs = []string{}
	}
	return policy, nil
}

func (s *Store) SetRequestPolicy(ctx context.Context, policy RequestPolicy) error {
	policy.UpdatedAt = time.Now().UTC()
	raw, err := json.Marshal(policy)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, `
		INSERT INTO app_settings (key, value, updated_at)
		VALUES ($1, $2::jsonb, now())
		ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
		RequestPolicyKey, string(raw))
	if err != nil {
		return fmt.Errorf("store: write request policy: %w", err)
	}
	return nil
}

// Maintenance is the operator switch that takes Memby down independently of Emby.
//
// Deliberately durable: a restart must not quietly bring the app back up while someone
// is still working on it.
type Maintenance struct {
	Enabled   bool      `json:"enabled"`
	Message   string    `json:"message"`
	UpdatedAt time.Time `json:"updatedAt"`
}

// DefaultMaintenanceMessage is shown on the TV when the operator did not write one.
const DefaultMaintenanceMessage = "Memby is down for maintenance. Try again shortly."

func (s *Store) Maintenance(ctx context.Context) (Maintenance, error) {
	var raw []byte
	err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, MaintenanceKey).Scan(&raw)
	if errors.Is(err, pgx.ErrNoRows) {
		return Maintenance{}, nil
	}
	if err != nil {
		return Maintenance{}, fmt.Errorf("store: read maintenance: %w", err)
	}

	var state Maintenance
	if err := json.Unmarshal(raw, &state); err != nil {
		return Maintenance{}, fmt.Errorf("store: decode maintenance: %w", err)
	}
	return state, nil
}

func (s *Store) SetMaintenance(ctx context.Context, state Maintenance) error {
	state.UpdatedAt = time.Now().UTC()
	raw, err := json.Marshal(state)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, `
		INSERT INTO app_settings (key, value, updated_at)
		VALUES ($1, $2::jsonb, now())
		ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
		MaintenanceKey, string(raw))
	if err != nil {
		return fmt.Errorf("store: write maintenance: %w", err)
	}
	return nil
}

// UpdatePolicyKey is the app_settings row backing the client update policy.
const UpdatePolicyKey = "update_policy"

func (s *Store) UpdatePolicy(ctx context.Context) (appupdate.Policy, error) {
	var raw []byte
	err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, UpdatePolicyKey).Scan(&raw)
	if errors.Is(err, pgx.ErrNoRows) {
		return appupdate.Policy{}, nil
	}
	if err != nil {
		return appupdate.Policy{}, fmt.Errorf("store: read update policy: %w", err)
	}

	var policy appupdate.Policy
	if err := json.Unmarshal(raw, &policy); err != nil {
		return appupdate.Policy{}, fmt.Errorf("store: decode update policy: %w", err)
	}
	return policy, nil
}

func (s *Store) SetUpdatePolicy(ctx context.Context, policy appupdate.Policy) error {
	policy.UpdatedAt = time.Now().UTC()
	raw, err := json.Marshal(policy)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, `
		INSERT INTO app_settings (key, value, updated_at)
		VALUES ($1, $2::jsonb, now())
		ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
		UpdatePolicyKey, string(raw))
	if err != nil {
		return fmt.Errorf("store: write update policy: %w", err)
	}
	return nil
}

// NewestSession is the fallback credential for the library import: whichever TV signed
// in most recently. It means a fresh deployment can import without configuring a
// service account, at the cost of the import stopping if that user is ever removed.
func (s *Store) NewestSession(ctx context.Context) (Session, error) {
	var sess Session
	err := s.pool.QueryRow(ctx, `
		SELECT token_hash, emby_user_id, emby_token, username, server_id, device_id,
			device_name, client_version, client_protocol, client_capabilities, last_seen_at
		FROM sessions ORDER BY last_seen_at DESC LIMIT 1`).
		Scan(&sess.TokenHash, &sess.EmbyUserID, &sess.EmbyToken, &sess.Username,
			&sess.ServerID, &sess.DeviceID, &sess.DeviceName, &sess.ClientVersion,
			&sess.ClientProtocol, &sess.ClientCapabilities, &sess.LastSeenAt)
	if errors.Is(err, pgx.ErrNoRows) {
		return Session{}, ErrNotFound
	}
	if err != nil {
		return Session{}, fmt.Errorf("store: newest session: %w", err)
	}
	return sess, nil
}
