-- Migration 000029: More cross-roads so every town has at least three direct neighbors
-- (ring + shortcuts). Complements 000027 for hubs that still had only two outgoing roads
-- (Starfall, Duskwatch, Boghollow).

-- Starfall <-> Mossharbor (Starfall otherwise only: Cinderkeep, Willowdale)
INSERT INTO roads (from_town_id, to_town_id, distance)
SELECT f.id, t.id, 1600.0
FROM towns f, towns t
WHERE f.name = 'Starfall' AND t.name = 'Mossharbor'
  AND NOT EXISTS (SELECT 1 FROM roads r WHERE r.from_town_id = f.id AND r.to_town_id = t.id);

INSERT INTO roads (from_town_id, to_town_id, distance)
SELECT f.id, t.id, 1600.0
FROM towns f, towns t
WHERE f.name = 'Mossharbor' AND t.name = 'Starfall'
  AND NOT EXISTS (SELECT 1 FROM roads r WHERE r.from_town_id = f.id AND r.to_town_id = t.id);

-- Duskwatch <-> Frostmark (Duskwatch otherwise only: Redcliff, Boghollow)
INSERT INTO roads (from_town_id, to_town_id, distance)
SELECT f.id, t.id, 1400.0
FROM towns f, towns t
WHERE f.name = 'Duskwatch' AND t.name = 'Frostmark'
  AND NOT EXISTS (SELECT 1 FROM roads r WHERE r.from_town_id = f.id AND r.to_town_id = t.id);

INSERT INTO roads (from_town_id, to_town_id, distance)
SELECT f.id, t.id, 1400.0
FROM towns f, towns t
WHERE f.name = 'Frostmark' AND t.name = 'Duskwatch'
  AND NOT EXISTS (SELECT 1 FROM roads r WHERE r.from_town_id = f.id AND r.to_town_id = t.id);

-- Boghollow <-> Ashengard (Boghollow otherwise only: Duskwatch, Cinderkeep)
INSERT INTO roads (from_town_id, to_town_id, distance)
SELECT f.id, t.id, 1500.0
FROM towns f, towns t
WHERE f.name = 'Boghollow' AND t.name = 'Ashengard'
  AND NOT EXISTS (SELECT 1 FROM roads r WHERE r.from_town_id = f.id AND r.to_town_id = t.id);

INSERT INTO roads (from_town_id, to_town_id, distance)
SELECT f.id, t.id, 1500.0
FROM towns f, towns t
WHERE f.name = 'Ashengard' AND t.name = 'Boghollow'
  AND NOT EXISTS (SELECT 1 FROM roads r WHERE r.from_town_id = f.id AND r.to_town_id = t.id);

-- Waypoints for new roads only (same rule as 000019 / 000027).
INSERT INTO road_waypoints (road_id, seq, x, y)
SELECT
    r.id,
    gs.seq,
    CASE
        WHEN gs.seq = 0 THEN f.world_x
        WHEN gs.seq = seg.nseg THEN t.world_x
        ELSE f.world_x + (t.world_x - f.world_x) * (gs.seq::double precision / seg.nseg::double precision)
    END,
    CASE
        WHEN gs.seq = 0 THEN f.world_y
        WHEN gs.seq = seg.nseg THEN t.world_y
        ELSE f.world_y + (t.world_y - f.world_y) * (gs.seq::double precision / seg.nseg::double precision)
    END
FROM roads r
INNER JOIN towns f ON f.id = r.from_town_id
INNER JOIN towns t ON t.id = r.to_town_id
LEFT JOIN road_waypoints rw ON rw.road_id = r.id
CROSS JOIN LATERAL (
    SELECT GREATEST(
        1,
        FLOOR(
            SQRT(POWER(t.world_x - f.world_x, 2) + POWER(t.world_y - f.world_y, 2)) / 20.0
        )::integer
    ) AS nseg
) seg
CROSS JOIN LATERAL generate_series(0, seg.nseg) AS gs(seq)
WHERE rw.road_id IS NULL;
